Reputation: 37
I have a list of inputs:
<input type='checkbox' name='182,500' value='182,500'> Below QAR 182,500
<input type='checkbox' name='182,500plus' value='182,500plus'> Above QAR 182,500 – Below QAR 365,000
<input type='checkbox' name='365,000' value='365,000'> Above QAR 365,000
<span class="custom-link btn border-width-0 info-submit btn-color-xsdn btn- outline btn-icon-left">Submit</span>
I want to restrict it to one checked box at a time. I tried doing so using this:
if ($("[name='182,500']").prop('checked')) {
$("[name='182,500plus']").prop('checked', false);
$("[name='365,000']").prop('checked', false);
} else if ($("[name='182,500plus']").prop('checked')) {
$("[name='182,500']").prop('checked', false);
$("[name='365,000']").prop('checked', false);
} else if ($("[name='365,000']").prop('checked')) {
$("[name='182,500']").prop('checked', false);
$("[name='182,500plus']").prop('checked', false);
}
but for some reason it's not working, any idea how can I fix that?
Upvotes: 1
Views: 153
Reputation: 3560
Your have an issue in event, you need to use on change event to trigger any code you want. Also you can improve your code to be like this:
$('.chTrigger').on('change', function(){
$('.chTrigger').not($(this)).prop('checked', false);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='checkbox' class="chTrigger" name='182,500' value='182,500'> Below QAR 182,500
<input type='checkbox' class="chTrigger" name='182,500plus' value='182,500plus'> Above QAR 182,500 – Below QAR 365,000
<input type='checkbox' class="chTrigger" name='365,000' value='365,000'> Above QAR 365,000
<span class="custom-link btn border-width-0 info-submit btn-color-xsdn btn- outline btn-icon-left">Submit</span>
Note: @Hans Dash comment is nice if you want a radio behavior. @Hans Dash Say:
If you want to restrict the user to making only one choice, you should use radiobuttons instead of checkboxes. This works two ways: it is clear for the user and the desired behavior is build in
Upvotes: 1