92sharmasaurabh
92sharmasaurabh

Reputation: 166

Checkbox not getting checked after radio button change event

I have a checkbox and two radio button. On change event of one of the radio, I am making checked attribute of checkbox true. It works only once.

Demo

Step to replicate it, 1. click on ugly (checkbox is checked) 2. uncheck the checkbox 3.toggel btw ugly and good(no effect :(

Spent a lot of time on this, but couldn't figure out what's going on.

Upvotes: 2

Views: 44

Answers (2)

prasanth
prasanth

Reputation: 22500

Try this if condition .clicked radio button value is bad the clicked true are else false appear in checked attr .You should use prop() method instead of attr

updated

Why not working?
you selector was wrong .you have $('input[type=radio][value = "bad"]') .its select only value bad radio button not for both .So only if you click other radio button the checkbox was not unchecked

$(document).ready(function() {
  $('input[type=radio]').on('change', function() {
    $('.xyz').prop('checked',   $(this).val().trim() == 'bad');
  })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script data-require="jquery" data-semver="3.1.1" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<input type="checkbox" name="vehicle" value="Car" class="xyz"> I have a car<br>
<input type="radio" name="gender" value="good"> Good Oned<br>
<input type="radio" name="gender" value="bad"> Ugly<br><br>

Upvotes: 1

Pranav C Balan
Pranav C Balan

Reputation: 115222

Update your code as follows:

  1. Use prop() method instead of attr() method to update the checked property.
  2. Bind change event handler commonly and update the property based on selected radio button value.

// or select based on the name attribute
// `$('input[type=radio][name="gender"]')`
$('input[type=radio]').on('change', function() {
  $('.xyz').prop('checked', this.value == 'bad');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="vehicle" value="Car" class="xyz"> I have a car<br>


<input type="radio" name="gender" value="good"> Good Oned<br>
<input type="radio" name="gender" value="bad"> Ugly<br>

Upvotes: 1

Related Questions