0

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>
Jack
  • 13
  • 4

3 Answers3

1

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);
inon
  • 1,689
  • 1
  • 19
  • 34
  • I've changed .attr('checked', false); to .prop('checked', false); and attr('checked', true); to .prop('checked', true); but that doesn't work.. I wan't check/uncheck a box, if a box is checked then uncheck the other box and I want to add a class to the parent label. – Jack May 15 '17 at 08:14
1

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>
4b0
  • 21,981
  • 30
  • 95
  • 142
  • Yes, this is almost working for me. If you uncheck the checked box then the class won't be removed. It's been removed if you click the other box. – Jack May 15 '17 at 08:22
0

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").

Community
  • 1
  • 1
Zuks
  • 1,247
  • 13
  • 20