I have a set of simple checkboxes, that can check multiple option, but I wish it to behave like a radio button where there will always be one option that is checked.
as you can see in my code, the checkbox will checked, and than uncheck. please let me know what I did wrong. Thanks
event.preventDefault()
makes your .prop
not working
You'll also need to uncheck others when a checkbox is checked.
$('input[type=checkbox]').on('click', function(event) {
// Remove this line
// event.preventDefault();
if ($('input[type=checkbox]:checked').length === 1) {
if ($(this).is(':checked')) {
return false; // this is checked
}
return false; // and this is the only one check
} else {
// Uncheck others
$('input[type=checkbox]').prop('checked', false);
$(this).prop('checked', true);
alert($(this).prop('checked')); // this return true
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<input type="checkbox" checked="checked" />
<input type="checkbox" />
<input type="checkbox" />