Last Updated on August 15, 2022 by Roshan Parihar
In this tutorial, learn how to make the HTML checkbox Group Single Selection using jQuery. The short answer is to use the prop()
function to uncheck the non-required checkboxes.
There can be many other methods to allow users to select only a single checkbox in a form. Let’s find out with the examples given below to learn the methods.
Method 1: Using jQuery prop() with not() to make Checkbox Group with Single Selection
If you want to make a checkbox group in HTML with a single selection for users, you have to use the click event of jQuery and use the prop()
. The function takes two arguments in which the first argument is checked
and the second argument is false
. It also requires using the not
to make only the clicked checkbox checked.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<script> $(document).ready(function(){ $('input[name="counting"]').click(function(){ $('input[name="counting"]').not(this).prop('checked', false); }); }); </script> <form> <input type="checkbox" name="counting" value="One"> One <input type="checkbox" name="counting" value="Two"> Two <input type="checkbox" name="counting" value="Three"> Three <input type="checkbox" name="counting" value="Four"> Four <input type="checkbox" name="counting" value="Five"> Five </form> |
Output
The above examples contain checkboxes in groups with the same name. When you click the checkbox given above, it will allow you to select only one option and not more than one selection.
This is useful when you want the users to give only a single data from the multiple options.
Method 2: Use Radio Button with Same Name Using <input type=”radio”>
In addition to the above example, you can also use the radio buttons in place of the checkboxes. You have to use the same name for all the radio buttons to allow users to select only a single selection.
1 2 3 4 5 6 7 |
<form> <input type="radio" name="color" value="Red"> Red <input type="radio" name="color" value="Green"> Green <input type="radio" name="color" value="Blue"> Blue <input type="radio" name="color" value="Yellow"> Yellow <input type="radio" name="color" value="Brown"> Brown </form> |
Output
The above example contains many radio buttons to select a color of your choice. You are allowed to select only a single radio button. This is a simple and easier method to allow a single selection in HTML for multiple choices.
Radio also works in HTML to give a single select option without the need to use any jQuery.
You May Also Like to Read