Jack
Jack

Reputation: 13

Can't deselect checkbox (jQuery)

I've got 2 checkboxes, if you check one box the other box will be deselected. But for some reason I can't deselect the box that has been checked

jQuery(document).ready(function(){
  jQuery("input[type='checkbox']").on('click', function () {
    jQuery("input[type='checkbox']").removeClass('selected').attr('checked', false);
    jQuery("input[type='checkbox']").parent().removeClass('selected');
    jQuery(this).parent().addClass('selected')
    jQuery(this).attr('checked', true);
  });

Any idea why this is happening?

solution (thanks to Shree)

$('input.example').on('change', function() {
if($(this).is(':checked'))
{
  $('input.example').not(this).prop('checked', false);
  $('input.example').parent().removeClass('selected');
  $(this).parent().addClass('selected');
}
else
{
  $('input.example').parent().removeClass('selected');
}
});
.selected {
  background-color:red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <input type="checkbox" class="example" />
</div>
<div>
  <input type="checkbox" class="example" />
</div>

Upvotes: 0

Views: 929

Answers (3)

4b0
4b0

Reputation: 22323

For this you can use class with not selector.

$('input.example').on('change', function() {
if($(this).is(':checked'))
{
  $('input.example').not(this).prop('checked', false);
  $('input.example').parent().removeClass('selected');
  $(this).parent().addClass('selected');
}
else
{
  $('input.example').parent().removeClass('selected');
}
});
.selected {
  background-color:red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <input type="checkbox" class="example" />
</div>
<div>
  <input type="checkbox" class="example" />
</div>

Upvotes: 1

Zuks
Zuks

Reputation: 1307

This explains the history of "attr" vs "prop" in jquery well: https://stackoverflow.com/a/13247188/3514785

1): Use "prop" to select/deselect checkboxes

2): attr("checked",false) would not remove "checked" but rather give it the value "false". If you really wanted to use "attr" you should rather use removeAttr... As in removeAttr("checked").

Upvotes: 0

inon
inon

Reputation: 1772

In jQuery, If you want to set the "Checked" property in "input" with type "checkbox", You need use:

$('input#id').prop('checked', true);

or

$('input#id').prop('checked', false);

Upvotes: 1

Related Questions