Jquery - Uncheck Other Checkboxes If A Specific Checkbox Is Selected By User
I would like to uncheck all the checkboxes that are presently selected if a specific checkbox is selected by the user. Example:
Solution 1:
for the label
instead of id
I think you need for
<div><labelfor="foo"><inputtype="checkbox"name="foo"id="foo"checked /> foo
</label></div><div><labelfor="bar"><inputtype="checkbox"name="bar"id="bar"checked /> bar
</label></div><div><labelfor="foobar"><inputtype="checkbox"name="foobar"id="foobar" /> foobar
</label></div><div><labelfor="barfoo"><inputtype="checkbox"name="barfoo"id="barfoo"checked /> barfoo
</label></div><div><labelfor="omgwtfbbq"><inputtype="checkbox"name="omgwtfbbq"id="omgwtfbbq" /> omgwtfbbq
</label></div>
then
var $others = $('input[type="checkbox"][name="meh"]').not('#omgwtfbbq')
$('#omgwtfbbq').change(function () {
if (this.checked) {
$others.prop('checked', false)
}
});
$others.change(function () {
if (this.checked) {
$('#omgwtfbbq').prop('checked', false)
}
})
Demo: Fiddle
Note: I'll add a common class to all the input elements which has to be affected by omgwtfbbq
and change var $others = $('#foo, #bar, #foobar, #barfoo')
to var $others = $('.myclassoninput')
Solution 2:
$('#omgwtfbbq').click(function() {
$('input:checkbox').not(this).attr('checked', false);
});
Also note that you're re-using id's. Id's should only be used once in a document.
Solution 3:
If you choose not to give each checkbox a sequential IDs so that you can use an array, here's a solution:
Place all your controls in a div, with an ID "checkgroup".
Then the JavaScript function goes:
function checkone(d){
if (!d.checked) return; //if it's unchecked, then do nothingvargroup=document.getElementById('checkgroup');
var os=group.getElementsByTagName('input');
for (var i=0;i<os.length;i++){
if (os[i].checked&&os[i]!=d) os[i].checked=false;
}
}
Now you can call this function in each checkbox
<div id="checkgroup">
<input id="abcd" onclick="checkone(this);">
<input id="xyz" onclick="checkone(this);">
...
</div>
Note how you don't even need to bother with the name, because the object passes in itself.
Post a Comment for "Jquery - Uncheck Other Checkboxes If A Specific Checkbox Is Selected By User"