Checkbox disable in angular - javascript

I have a table. I have a column which has only checkboxes as values in it. I have brought all values into a table using for loop.What I did was when I enable a checkbox, I showed a message "hey" When I enable one checkbox (the message appears) but when I enable another checkbox the message disappears.The message initially comes when even one checkbox gets enabled. What I need is that until all the checkbox gets disabled the message should be there and evenwhen one or more checkboxes are there the message should be there.I am writing my code in angular.
Here is my stackblitz link
https://stackblitz.com/edit/angular-oswf2h?file=src%2Fapp%2Fapp.component.ts

You should store the input values and provide a result based on the stores values.
Example with ngModel:
checkedValues: boolean[] = this.a.map(() => false);
get isChecked() {
return this.checkedValues.some(b => b);
}
<div>
<div class="Container" style="margin-left: 10px;">
<div class="table-responsive">
<table class="table">
<thead class="table_header">
<tr>
<th>Name</th>
<th>Checkbox</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let b of a; let i = index">
<td>{{b.name}}</td>
<td> <input type="checkbox" id="vehicle1" name="vehicle1" [(ngModel)]="checkedValues[i]">
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div *ngIf="isChecked">
<h1>Hey</h1>
</div>
</div>
Changed stackblitz: https://stackblitz.com/edit/angular-jwpane?file=src/app/app.component.html

I changed up you code a bit to make it work. There could be many ways to do this, but i decided to try as little as possible changes.
Store the check state for each separate checkbox.
a = [
{ name: "a", check: false },
{ name: "b", check: false },
{ name: "c", check: false }
];
On checkBtn press receive the item from front end and go through all items to see if all are disabled
checkBtn(b) {
b.check = !b.check;
let check = false;
this.a.forEach(item => {
if (item.check) {
check = true;
}
});
this.ischeck = check;
}
Finally pass the item from frontend
<tr *ngFor="let b of a;">
<td>{{b.name}}</td>
<td> <input type=" checkbox" id="vehicle1" name="vehicle1" (click)=" checkBtn(b)">
</td>
</tr>

The problem is that all your checkboxes are connected to the same boolean, so they just toggle it. When one is clicked, regardless of whick one, ischeck gets the value of true. When a checkbox is clicked, either the same one or a different one, it gets toggled again so now ischeck is false.
One possible solution is to have a different check per each checkbox, and display the message based on a logical OR.
See this stackblitz solution here
updated ts file:
ischeck: boolean = false;
a = [
{ name: "a", isCheck: false },
{ name: "b", isCheck: false },
{ name: "c", isCheck: false }
];
checkBtn(b: { name: string; isCheck: boolean }) {
b.isCheck = !b.isCheck;
this.ischeck = this.a.some(c => c.isCheck); // at least one item has checked as
}
and change in HTML:
<input type=" checkbox" id="vehicle1" name="vehicle1" (click)=" checkBtn(b)">
EDIT:
updated the code to simulate getting data from a service
ts simulation:
a = [];
ngOnInit() {
this.a = [{ name: "a" }, { name: "b" }, { name: "c" }]; //returned from service
this.a.map(v => { //data changes to add boolean
return { ...v, isCheck: false };
});
}

Related

How do I find a radio button by value to check it with another element - VueJS

I apologize for the title being a little hard to understand. I had a hard time explaining it in one line. But here's what I'm trying to do.
I'm developing a screen within my app that supports a barcode gun reader. Barcode guns can only interact with textfields. And then through a text field(hidden) I can pass a custom barcode that instructs the UI to do something. Here is the UI explanation for clarity:
I have a radio button group with 2 options (yes and no)
I have a hidden textfield to accept the barcode gun read
I have a barcode for "yes" and another for "no"
If I scan the "yes" barcode, the radio button option with value = "Yes", should be checked
If I scan the "no" barcode, the radio button option with value = "No", should be checked
I initially thought that by changing the v-model to the correct value, it will do it, but it didn't check it. Likewise, by changing the v-model.value to true or false it will check to its appropriate value. But no cigar.
My idea on how this would work is by (pseudocode)
if querySelector with name ragrouphidden.value = "Yes" then find the option whose value is Yes and option.checked = true
else if querySelector with name ragrouphidden.value = "No" then find the option whose value is No and option.checked = true
The "find" part is what eludes me, or maybe there is an easier way.
Here's some relevant code
Template
<div>
<q-input
class="hidden-field"
v-model="ragrouphidden"
name="ragrouphidden"
#change="raSelectOption()">
</q-input>
<div>
<label class="col-6 text-weight-medium">Mark for Remote Adjudication</label>
<div>
<q-option-group
v-model="ragroup"
:options="raoptions"
#check="raRules($event.target.value)"/>
</div>
</div>
</div>
Script
data() {
return {
ragrouphidden: "",
ragroup: null,
raoptions: [
{
label: "Yes",
value: true
},
{
label: "No",
value: false
}
],
}
},
methods: {
raSelectOption() {
setTimeout(() => {
let hasFocus = document.querySelector("input[name=ragrouphidden]");
hasFocus.focus();
}, 500);
if (
document.querySelector("input[name=ragrouphidden]").value === "*yes*"
) {
this.ragroup.value = true; //this is what I need
} else if (
document.querySelector("input[name=ragrouphidden]").value === "*no*"
) {
this.ragroup.value = false; //This as well
}
},
}
Hopefully it makes sense to you guys. Thanks in advance.
You don't need to use ragroup.value to set the model value here. You can simply do this.ragroup = true; and vue will automatically set the q-option-group selected value for you behind the scene.
A simple demo with dynamic checkbox:
var demo = new Vue({
el: '#demo',
data: {
checked: [],
categories: [{ Id: 1 }, { Id: 2 }]
},
mounted(){ this.checked = [2] }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<div id="demo">
<ul>
<li v-for="c in categories">
<input type="checkbox" :value="c.Id" :id="c.Id" v-model="checked" />
{{c.Id}}
</li>
</ul>
</div>

AngularJS - Checklist-Model doesn't update the model correctly on checkbox change

I'm new to AngularJS and I'm having a problem with the Checklist-Model directive.
I'm using one of their examples to replicate this behavior.
When I click one checkbox and call a function, the model seems to be updated
correctly and is shown accordingly on the template, but when I log the contents of the model on the console the value of the checkbox I clicked is missing.
Here's when the strange stuff starts. If I click the checkbox again, then the value is removed from the template but I can see it on the console.
Here's the code:
HTML:
<div ng-controller="DemoCtrl">
<label ng-repeat="role in roles">
<input type="checkbox" checklist-model="user.roles"
checklist-value="role.text"
ng-change="changeValues(role)"> {{role.text}}
</label>
<br>
<button ng-click="checkAll()">check all</button>
<button ng-click="uncheckAll()">uncheck all</button>
<button ng-click="checkFirst()">check first</button>
<br><br>
user.roles {{ user.roles | json }}
</div>
Angular:
angular.module("DemoApp", ["checklist-model"])
.controller('DemoCtrl', function($scope) {
$scope.roles = [
{id: 1, text: 'guest'},
{id: 2, text: 'user'},
{id: 3, text: 'customer'},
{id: 4, text: 'admin'}
];
$scope.user = {
roles: ['guest', 'admin']
};
$scope.checkAll = function() {
$scope.user.roles = $scope.roles.map(function(item) { return item.id; });
};
$scope.uncheckAll = function() {
$scope.user.roles = [];
};
$scope.checkFirst = function() {
$scope.user.roles.splice(0, $scope.user.roles.length);
$scope.user.roles.push(1);
};
$scope.changeValues = function() {
console.log('Roles: ', JSON.stringify($scope.user.roles));
}
});
The first time I click a checkbox i.e: 'User' the output on the console is:
Roles: ["guest","admin"]
Then, when I uncheck the same checkbox the output is:
Roles: ["guest","admin","user"]
In the application I'm developing I MUST call a function when the checkbox changes it's value that's why I using the "ng-change" directive.
Can anybody explain what I'm doing wrong?
Thanks in advance.
checklist-model it's used the Id as checklist-value in the checkbox and in your code you use the text.
So in the function $scope.checkAll you should return the item.text instead item.id and in the function $scope.checkFirst you should push the $scope.roles.find(item => item.id == 1).text
And the rest seems correct

Checkboxes to be checked after saving in angularjs

I am using angularjs for my application.I am using multiple checkbox selection and storing it in database in the format [1,2,3,4,5].For example if the checkbox selected is 1 then i am storing the value as 1.If multiple are selected then 1,2,3, and so on.
Here is the html
<div class="col-xs-12">
<div data-ng-repeat="healthStatus in HealthStatuses">
<input id="chkCustomer_{{healthStatus.Value}}" value="
{{healthStatus.Value}}" type="checkbox"
data-ng-checked="selection.indexOf(healthStatus.Value) > -1"
data-ng-click="toggleSelectionHealthStatus(healthStatus.Value)" />
{{healthStatus.Name}}</label>
</div>
</div>
Here is the controller.js
$scope.HealthStatuses = [{
Name: 'Alzheimers',
Value: 1,
Selected: false
}, {
Name: 'Arthritis',
Value: 2,
Selected: false
},{
Name: 'Cancer',
Value: 3,
Selected: false
},{
Name: 'Cellulitis',
Value: 4,
Selected: false
}];
Here is how i am pushing the selected checkboxes value
$scope.selectionHealthStatus=[];
$scope.toggleSelectionHealthStatus = function toggleSelection(Value) {
var idx = $scope.selectionHealthStatus.indexOf(Value);
if (idx > -1) {
$scope.selectionHealthStatus.splice(idx, 1);
} else {
$scope.selectionHealthStatus.push(Value);
}
};
Now while retrieving the data i want the checkboxes to be checked.But now it is not happening.
Here is how i am retrieving the data
userPageService.getHealthStatus().then((data) => {
data = data.data;
$scope.formData = data;
});
If i put console for $scope.formData this is what i get.
participantIllnessAndDisability:"[1, 2, 3, 4]"
Here participantIllnessAndDisability is one field with multiple checkboxes selected.Now what i want to do is after adding the data while viewing i want the selected checkboxes to be checked.I am getting the data from database in [1,2,3] format.The datatype for field participantIllnessAndDisability in database is String.
At load of page, the function on ng-checked won’t get automatically called. Hence it won’t check the check box.
You could assign ng-model or ng expression to checked property and initialize it from controller on data load.
Update:
Please try this.
userPageService.getHealthStatus().then((data) => {
data = data.data;
$scope.formData = data;
$scope.HealthStatuses.forEach((o) => o.Selected = JSON.parse(data.participantIllnessAndDisability).includes(o.Value));
});

Check box selection in table using AngularJS

I am trying to create a method that receives an Id from the table, when a checkbox has been checked, and should update the $scope.selected in the angular controller.
And when the checkbox is uncheked, then it should remove it from the $scope.selected again.
So far it looks like this:
$scope.updateselection = function(id) {
if ($scope.selected(sort_id) != id) { //what is the correct syntax here??
$scope.selected.push({ sort_id: id });
} else {
$scope.selected.remove({ sort_id: id });
}
};
For interaction with ckeckboxes in Angular I've recommend to use the following directive: http://vitalets.github.io/checklist-model/
If you don't want to use this directive, you can create watcher on your checkboxes table.
For example:
HTML:
<table>
<tr>
<td ng-repeat="item in items">
<input type="checkbox" ng-model="item.value">
</td>
</tr>
<table>
JS:
$scope.items = [
{
name: "name1",
value: true
},
{
name: "name2",
value: false
}
];
$scope.selectedItems = [];
$scope.$watch('items', function(newValues){
$scope.selectedItems.length = 0;
angular.forEach(newValues, function(item) {
if (item.value == true) {
$scope.selectedItems.push(item.name);
}
});
console.log($scope.selectedItems);
}, true);
This way will allow you to always have the actual information about the selected checkbox.
I've created JSFiddle with working example for you.

Dependent combo box populating in Dojo Dijit?

I have a dojo combobox which when the options are changed i need to populate a related second combo box
which is co dependent on the value of the first combo box. How can i achieve this. The code i have tried so far is below
html code:
<div class="gis_SearchDijit">
<div class="formContainer">
<div data-dojo-type="dijit.form.Form" data-dojo-attach-point="searchFormDijit">
<table cellspacing="5" style="width:100%; height: 49px;">
<tr>
<td>
<label for="Customer">Customer:</label>
<div data-dojo-type="dijit.form.ComboBox" id="Customer"></div> <br />
<label for="Attributes">Search Attribute:</label>
<div data-dojo-type="dijit.form.ComboBox" id="Attributes"></div>
<br />
Enter Attribute Value:<input id="searchText" type="text" data-dojo-type="dijit.form.ValidationTextBox" data-dojo-props="name:'searchText',trim:true,required:true,style:'width:100%;'"
/>
</td>
</tr>
</table>
</div>
</div>
<div class="buttonActionBar">
<div data-dojo-type="dijit.form.Button" data-dojo-props="busyLabel:'searching',iconClass:'searchIcon'" data-dojo-attach-event="click:search">
Search
</div>
</div>
postCreate: function () {
this.inherited(arguments);
this.populateCmbCustomer(Memory);
var comboBoxDigit = registry.byId("Customer");
comboBoxDigit.on('change', function (evt) {
alert('on change'); //This alert is triggerd
this.populateCmbCustomerAttribute(Memory);
});
populateCmbCustomer: function (Memory) {
var stateStore = new Memory({
data: [
{ name: "Cust Data", id: "CUST" },
{ name: "Owner Data", id: "Owner" },
{ name: "Applicant", id: "Applicant" }
]
});
var comboBoxDigit = registry.byId("Customer");
//console.log("COMBO: ", comboBoxDigit);
comboBoxDigit.set("store", stateStore);
},
populateCmbCustomerAttribute: function (Memory) {
var custAttribute = new Memory({
data: [
{ name: "Custid", id: "Cust" },
{ name: "Applicant Id", id: "Applicant" },
{ name: "Owner_Id", id: "Owner" }
]
});
var CmbCustomerAttribute = registry.byId("Attributes");
CmbCustomerAttribute.set("store", custAttribute);
},
Note: the above is just part of the code of my widjet.js.
I am able to load the first combobox with the options. So now when i chose 'Cust Data' in my first combobox then custid should be the only option in second combo box. In the same way Owner Data in first then Owner_id in second...But so far i am not able to populate the second combo-box.. Can some one please guide me
Than You in advance
you should use the query property of the second combo it should look something like this
comboBoxDigit.on('change', function (evt) {
var CmbCustomerAttribute = registry.byId("Attributes");
CmbCustomerAttribute.set("query", {filteringProperty: this.get('value')}); //if you dont understand this check out the stores tutorials
});
EDIT: tutorials referenced in above code snippet helps clear up the ambiguity of "filteringProperty" quite a bit.
I would also recomend to populate your sencond combo from the beggining with something like this
var CmbCustomerAttribute = registry.byId("Attributes");
CmbCustomerAttribute.set("store", store);
CmbCustomerAttribute.set("query", {id:'nonExistantId'}); //so nothing shows in the combo
I think somthing like this is what you are seraching for, any doubts just ask. as cant say mucho more whitout a fiddle or actual code

Categories