Reputation: 560
I have a group of checkboxes and a QUERY button so user can check a few things and click QUERY button to make a service call to return records. How to disable the QUERY button if none of the checkboxes are checked?
Below are the codes I wrote. The QUERY button got disabled when I first time unchecked all of them. But when I checked only one of checkboxes back again, the array "unchecked" became empty. please help!
_bindChkChangeEvent: function(){
var unchecked = [];
on(query('.chk'), 'change', lang.hitch(this, function(event) {
if(!event.target.checked){
if(unchecked.indexOf(event.target.id) < 0)
unchecked.push(event.target.id);
}
else{
if(unchecked.indexOf(event.target.id) > -1)
unchecked.splice(event.target.id);
}
this._switchQueryBtn(unchecked);
}));
},
_switchQueryBtn: function(unchecked){
if(unchecked.length == 10)
html.addClass(this.btnQuery, 'disabled');
else
html.removeClass(this.btnQuery, 'disabled');
},
Upvotes: 1
Views: 1146
Reputation: 73988
At the following link a working example, you can try to adopt this concept to your code (unfortunately the question contains only a partial code view).
https://jsfiddle.net/zmh7bbrf/
What the script does:
onChange
for each checkbox.showHideButton
actually contains the logic to show or hide the button.showHideButton
runs and button is being disabled.showHideButton
.The script could work with any number of checkboxes, just add their reference and modify the logic in showHideButton
function.
Notes:
You can use dijit/registry
to find references of your widgets, instead of using dojo/query
and querying the DOM directly as in the code in your original question.
More information on dijit/registry
can be found here:
https://dojotoolkit.org/reference-guide/1.10/dijit/registry.html
require(["dijit/form/CheckBox", "dijit/registry", "dijit/form/Button", "dojo/domReady!"], function(CheckBox, registry, Button) {
new CheckBox({
id: "checkBox0",
name: "checkBox0",
value: "option0",
checked: false,
onChange: function(event) {
showHideButton();
}
}, "checkBox0").startup();
new CheckBox({
id: "checkBox1",
name: "checkBox1",
value: "option1",
checked: false,
onChange: function(event) {
showHideButton();
}
}, "checkBox1").startup();
new Button({
label: "Click me!",
onClick: function() {;
}
}, "button").startup();
var showHideButton = function() {
var checkBox0 = registry.byId('checkBox0'),
checkBox1 = registry.byId('checkBox1'),
button = registry.byId('button');
if (!checkBox0.checked && !checkBox1.checked) {
button.set('disabled', true);
} else {
button.set('disabled', false);
}
};
showHideButton();
});
<input id="checkBox0" />
<label for="checkBox">Option 0</label>
<br>
<input id="checkBox1" />
<label for="checkBox">Option 1</label>
<br>
<button id="button" type="button"></button>
Upvotes: 1