Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncheck all other checkboxes

I need to clear all other checkboxes when a user clicks a checkbox. Pretty much the same behavior as a radio button. User clicks checkbox 'A' and checkboxes 'B' and 'C' are both unchecked. I am using jquery but I can't figure out how to accomplish this. Any ideas?

Here are how the checkboxes are set u:

    <div class="sales_block_one">
<span class="sales_box_option_set"><input type="checkbox" value="1" id="exopt10i11553501716" name="optset[0][id]" /><label for="exopt10i11553501716">Test  + &pound;100.00</label></span> 
<span class="sales_box_option_set"><input type="checkbox" value="2" id="exopt11i21553501716" name="optset[1][id]" /><label for="exopt11i21553501716">Test  + &pound; 200.00</label></span> 
<span class="sales_box_option_set"><input type="checkbox" value="3" id="exopt12i31553501716" name="optset[2][id]" /><label for="exopt12i31553501716">Test 3 + &pound;400.00</label></span> 
</div>
like image 746
Thomas Avatar asked Oct 14 '10 09:10

Thomas


People also ask

How do I unselect all checkboxes?

Clicking on the master checkbox selects all checkboxes; and unchecking it, deselects all checkboxes.

How do I uncheck a checkbox in Powerapps?

Use the "Reset" function, write the formula Reset(Checkbox1) on "OnSelect" property. Please click Accept as Solution, if this solution solved your issue.


1 Answers

if all the checkboxes are siblings, it's just like this,

$(':checkbox').change(function(){

   if (this.checked) {
      $(this).siblings(':checkbox').attr('checked',false);
   }

});

crazy demo

Well, if you really want to copy the behavior of the radio button, simple as this,

$(':checkbox').change(function(){
      this.checked = true;
      $(this).siblings(':checkbox').attr('checked',false);     
});

crazy demo


siblings is when the elements has one same parent/container.

sample

<div>

<input type="checkbox" /><label>A</label>
<input type="checkbox" /><label>B</label>
<input type="checkbox" /><label>C</label>
<input type="checkbox" />​<label>D</label>

</div>

in that, <input>s and <label>s are siblings.


In your case, which it's not siblings, you can do it this way,

$('.sales_block_one :checkbox').change(function() {
    var $self = this; // save the current object - checkbox that was clicked.
    $self.checked = true; // make the clicked checkbox checked no matter what.
    $($self).closest('span') // find the closest parent span...
        .siblings('span.sales_box_option_set') // get the siblings of the span
        .find(':checkbox').attr('checked',false); // then find the checbox inside each span and then uncheck it.
});​

crazy demo

more about traversing

like image 114
Reigel Avatar answered Oct 13 '22 13:10

Reigel