开发者

Uncheck all other checkboxes

开发者 https://www.devze.com 2023-01-19 19:34 出处:网络
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

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]"开发者_如何学Python /><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>


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


$("#checkboxA").click(function() {
    var checkedStatus = this.checked;
    $("#checkboxB_And_C_Selector").each(function() {
        this.checked = !checkedStatus;
    });
});
0

精彩评论

暂无评论...
验证码 换一张
取 消