Reputation: 166
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.
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
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
Reputation: 115222
Update your code as follows:
prop()
method instead of attr()
method to update the checked
property.// 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