Reputation: 1346
I have checkboxes that behave like radio buttons, so that only one checkbox can be selected within a group of checkboxes. They are grouped by input class.
But I also want to have the possibility to unselect the checkbox, which is now being prevented in my code.
How can I have all the checkboxes "unselectable" with this function? Thank you.
HTML:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input type="checkbox" name="fruit" value="fruit" class="classname">I like fruits
<br>
<input type="checkbox" name="vegetable" value="vegetable" class="classname">I like vegetables
JavaScript:
$(document).ready(function () {
var $unique = $('input.classname');
$unique.click(function () {
$unique.removeAttr('checked');
$(this).attr('checked', true);
});
});
Upvotes: 0
Views: 232
Reputation: 388316
You can try to handle only the select operation like
$(document).ready(function () {
var $unique = $('input.classname');
$unique.change(function () {
if (this.checked) {
$unique.not(this).prop('checked', false);
}
});
});
Demo: Fiddle
Upvotes: 3