[jquery] jQuery: Uncheck other checkbox on one checked

I am having total 6 checkbox ( may be add more in future ) and I want to allow only select one so when user checked any of them other should unchecked.

I tried with this code and works fine if I defined ID but now just wonder how to make it vice versa in efficient way so in future if I add more than it wont be a problem

$('#type1').click(function() {
     $('#type2').not('#type1').removeAttr('checked');
}); 

FYI, checkboxs are not sibling and are in different <td>

This question is related to jquery checkbox

The answer is


Bind a change handler, then just uncheck all of the checkboxes, apart from the one checked:

$('input.example').on('change', function() {
    $('input.example').not(this).prop('checked', false);  
});

Here's a fiddle


I think the prop method is more convenient when it comes to boolean attribute. http://api.jquery.com/prop/


I wanted to add an answer if the checkboxes are being generated in a loop. For example if your structure is like this (Assuming you are using server side constructs on your View, like a foreach loop):

<li id="checkboxlist" class="list-group-item card">
  <div class="checkbox checkbox-inline">
    <label><input type="checkbox" id="checkbox1">Checkbox 1</label>
    <label><input type="checkbox" id="checkbox2">Checkbox 2</label>
  </div>
</li>

<li id="checkboxlist" class="list-group-item card">
  <div class="checkbox checkbox-inline">
    <label><input type="checkbox" id="checkbox1">Checkbox 1</label>
    <label><input type="checkbox" id="checkbox2">Checkbox 2</label>
  </div>
</li>

Corresponding Jquery:

$(".list-group-item").each(function (i, li) {
  var currentli = $(li);
  $(currentli).find("#checkbox1").on('change', function () {
       $(currentli).find("#checkbox2").not(this).prop('checked',false);
  });

  $(currentli).find("#checkbox2").on('change', function () {
       $(currentli).find("#checkbox1").not(this).prop('checked', false);
  });
});

Working DEMO: https://jsfiddle.net/gr67qk20/


Try this

$("[id*='type']").click(
function () {
var isCheckboxChecked = this.checked;
$("[id*='type']").attr('checked', false);
this.checked = isCheckboxChecked;
});

To make it even more generic you can also find checkboxes by the common class implemented on them.

Modified...


$('.cw2').change(function () {
    if ($('input.cw2').filter(':checked').length >= 1) {
        $('input.cw2').not(this).prop('checked', false);
    } 
});


$('td, input').prop(function (){
    $(this).css({ 'background-color': '#DFD8D1' });
    $(this).addClass('changed');
});

Try this

 $(function() { 
  $('input[type="checkbox"]').bind('click',function() {
    $('input[type="checkbox"]').not(this).prop("checked", false);
  });
});

you could use class for all your checkboxes, and do:

$(".check_class").click(function() {
  $(".check_class").attr("checked", false); //uncheck all checkboxes
  $(this).attr("checked", true);  //check the clicked one
});