How to Allow Only One Checkbox to be Checked using jQuery


Generally, we use radio buttons to let a user select ONE option from a limited number of choices. Most of the cases radio buttons are ideal to select a single option from a group of the options. But sometimes you required to use the checkbox to do the same functionality like a radio button. If you want to allow the user to check only one checkbox from a group of the checkboxes, it can be done easily using jQuery.

At first, include the jQuery library.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

To modify the default functionality of checkboxes and use like the radio buttons, you need to restrict the user to select multiple checkboxes. Use the following code to allow only one checkbox to be checked using jQuery.
HTML

<input type="checkbox" name="skill" value="male"> Male
<input type="checkbox" name="skill" value="female"> Female
<input type="checkbox" name="skill" value="other"> Other

JavaScript

<script>
$(document).ready(function(){
    $('input:checkbox').click(function() {
        $('input:checkbox').not(this).prop('checked', false);
    });
});
</script>

You can use a class selector to allow only one checkbox to be checked with jQuery.
HTML

<input type="checkbox" name="skill" class="check" value="male"> Male
<input type="checkbox" name="skill" class="check" value="female"> Female
<input type="checkbox" name="skill" class="check" value="other"> Other

JavaScript

<script>
$(document).ready(function(){
    $('.check').click(function() {
        $('.check').not(this).prop('checked', false);
    });
});
</script>

Leave a reply