Jason
Jason

Reputation: 85

2 checkboxes and when I uncheck one, I want the other to be checked

I sort of have it working but it only works once. I check the first box and then uncheck it and the other box checks but then when I check and uncheck the first one again,it doesn't work.

This will basically be like a radio button but the second checkbox will be hidden so they will just need to check or uncheck the first box.

Here is my code:

$('input').on('change', function() {
  $(this).siblings().attr('checked', false);
  if ($(this).prop('checked') == false) {
    $(this).siblings().attr('checked', true);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" />
<input type="checkbox" />

Upvotes: 2

Views: 47

Answers (1)

Josh Crozier
Josh Crozier

Reputation: 241198

The problem in your case is that you're using the .attr() method to change the checked attribute of the sibling checkbox elements. Since you're changing the attribute, it will only work once. If you change it to .prop(), it should work as expected.

An easier approach would be to toggle the checked property of the sibling elements based on whether the current checkbox is checked. You could simply use !this.checked in your case:

$('input').on('change', function() {
  $(this).siblings().prop('checked', !this.checked);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" />
<input type="checkbox" />

Upvotes: 5

Related Questions