- Html Select Only One Checkbox in a Group
- Select only one checkbox in a group but have option to select more than one if it’s certain checkboxes
- Select only one checkbox in group
- Select only one checkbox in a group
- How to only have one checkbox checked at a time?
- Check only one checkbox in each row
- How to select only one checkbox from many checkboxes with Javascript or jquery?
- To select only one checkbox at a time and execute a particular task on a particular checkbox being selected or both of the checkboxes being unchecked
- How to Allow Only One Checkbox to Be Checked in HTML
- Creating the HTML Markup#
- Allow Only a Limited Number of Checkboxes to be Checked#
- Semantically Correct Way For Single Selects#
- Conclusion#
- Recommended
- How to Display Key-Value Pairs in React in a Table
- How to Rerender Component on Resize in React
- How to Easily Fetch and Display JSON in React
- How to select only one checkbox in html
- Html select only one checkbox in a group
- Select only one checkbox HTML
- How to make user select only one check box in a checkboxlist
Html Select Only One Checkbox in a Group
Select only one checkbox in a group but have option to select more than one if it’s certain checkboxes
var aCheckboxes = document.querySelectorAll("input[name='checkboxes[]']");
var aGroups = [ [1, 2, 3, 6], [4, 5]];
for (var i = 0; i < aCheckboxes.length; i++) < aCheckboxes[i].addEventListener("change", function(e) < checkGroups(e.target.value); //. call checkGroups. >);>
function enableCheckboxes() < for (var i = 0; i < aCheckboxes.length; i++) < aCheckboxes[i].disabled = false; >>
function checkGroups(sCheckboxVal) < var isOneChecked = false;
for (var x = 0; x < aCheckboxes.length; x++) < //Loop through all checkboxes if (aCheckboxes[x].checked === true) < //is checkbox is checked isOneChecked = true; >> enableCheckboxes(); //Enable all checkboxes
if (isOneChecked === true) < //Is at least one checkbox is checked check groups aGroups.forEach(function(aGroup) < //Loop throgh your groups if (aGroup.indexOf(parseInt(sCheckboxVal)) === -1) < //Is checkbox not in group. for (x = 0; x < aGroup.length; x++) < //. loop thorugh all checkboxes. document.querySelectorAll("input[value='" + aGroup[x] + "']")[0].disabled = true; //. and disable checkbox >> >); >>
Select only one checkbox in group
Select only one checkbox in a group
If you only want one item to be selectable in each group, then you should use radio buttons rather than checkboxes. Then users will expect and understand that only one item is selectable. And if you create a series of radio buttons with the same «name» attribute, then the browser will automatically only allow one of them to be selected.
If you use checkboxes, then even if you use javascript to achieve what you suggest, then your users are likely to be confused, as the normal use of checkboxes is to allow the selection of multiple items at the same time.
How to only have one checkbox checked at a time?
Here is an example without JQuery. Add a class to your inputs.When Clicked, uncheck everything, and then check the clicked input if it was not checked.
function check(input) < var checkboxes = document.getElementsByClassName("radioCheck"); for(var i = 0; i < checkboxes.length; i++) < //uncheck all if(checkboxes[i].checked == true) < checkboxes[i].checked = false; >> //set checked of clicked object if(input.checked == true) < input.checked = false; >else < input.checked = true; >>
Check only one checkbox in each row
I have managed to use radio button instead of checkboxes
Also this solution fixed my problem:
html select only one checkbox in a group
How to select only one checkbox from many checkboxes with Javascript or jquery?
function message() alert("You cant check more than 1 checkbox ")
>
document.querySelectorAll(".cgroup").forEach((chbx)=> chbx.addEventListener("change",(e)=> if(!e.target.checked) return;
var checkedbox = Array.from(document.querySelectorAll(".cgroup")).find(chbx=>chbx!=e.target&&chbx.checked)
if(checkedbox) e.target.checked = false
message()
>
>)
>)
To select only one checkbox at a time and execute a particular task on a particular checkbox being selected or both of the checkboxes being unchecked
uncheckOther(chk, event)
if (event) //uncheck all
this.checkboxes.forEach(x => if (x.checked == true)
x.checked = false;
>)
//check the selected
if (chk.checked == true) chk.checked = false;
> else chk.checked = true;
>
if (chk.value == "Request") console.log('Call Request API')
>
else if (chk.value == "Reservation") console.log('Call Reservation API')
>
>
else console.log('Call Both API')
>
>
How to Allow Only One Checkbox to Be Checked in HTML
When working with multiple checkboxes, a common use case is to limit the number of selectable options, preventing users from selecting more options than allowed. For example, you may have the following group of checkboxes where you only want a maximum of two options to be selected:
In this tutorial, we will take a look at how this can be achieved in HTML with the use of event listeners in JavaScript.
If you need to allow only one checkbox to be selected, use a radio group instead.
Level up your skills and master the art of frontend development with bite-sized tutorials.
We don’t spam. Unsubscribe anytime.
Looking to improve your skills? Check out our interactive course to master JavaScript from start to finish.
Creating the HTML Markup#
First, we need to create the input group in HTML. To do this, create the following layout in your HTML file:
span>You can only select up to two options.span> div> label for="html"> input type="checkbox" value="html" id="html" /> HTML label> label for="javascript"> input type="checkbox" value="javascript" id="javascript" /> JavaScript label> div>
To separate the input group from the rest of the layout, wrap it inside a div , which we will style shortly. To make the inputs accessible, wrap them inside a label . We can match a label with an input using the for attribute, which references the element’s id .
Make sure you caption the group to make it clear that users can only select a limited number of options.
To display the inputs below each other, we can set the display of the wrapping div to flex , and set the flex-direction to column :
div display: flex; flex-direction: column; >
Allow Only a Limited Number of Checkboxes to be Checked#
To get everything working, we need to attach a click event listener to the checkboxes in JavaScript. To avoid creating a separate listener for each checkbox, we can use event delegation:
const maxChecks = 2 let selectedCount = 0 document.querySelector('div').addEventListener('click', event => if (event.target.type === 'checkbox') selectedCount = event.target.checked ? selectedCount + 1 : selectedCount - 1 > if (selectedCount >= maxChecks) [. document.querySelectorAll('input:not(:checked)')].forEach(input => input.disabled = true) > else [. document.querySelectorAll('input')].forEach(input => input.disabled = false) > >)
In the example above, we set the maximum number of available options to two using the maxChecks variable. We also need to keep track of the number of selected checkboxes. This will be tracked in the selectedCount variable. Inside the event listener, we need to implement the following logic:
- Line 4: We attach the event listener to the div container so that we can delegate it to the checkboxes.
- Line 5: To determine if a checkbox was clicked, we can check if event.target.type is checkbox .
- Lines 6-8: In case a checkbox was clicked, we need to either increase or decrease the selectedCount variable. This is done using a ternary operator. If the checkbox is checked ( event.target.checked will be true ), then we increase the count by one; otherwise, we decrease it.
- Line 11: If the selectedCount reaches maxChecks , we need to select all checkboxes that are unchecked and disable them using the disabled property. We can select them using the :not(:checked) pseudo-class.
- Line 14: In case we haven’t reached the maximum allowed checkboxes, we re-enable every input by setting input.disabled to false . Note that since querySelectorAll returns a NodeList, we need to use the spread operator to convert it into a regular array so that we can use forEach .
Level up your skills and master the art of frontend development with bite-sized tutorials.
We don’t spam. Unsubscribe anytime.
Looking to improve your skills? Check out our interactive course to master JavaScript from start to finish.
Semantically Correct Way For Single Selects#
In case you need users to select only one option from many, the semantically correct way to achieve this is by using a radio group:
div> label for="html"> input type="radio" value="html" id="html" name="topic" checked /> HTML label> label for="javascript"> input type="radio" value="javascript" id="javascript" name="topic" /> JavaScript label> div>
Radio buttons can be grouped together, restricting users to select only one option. In the example below, you can experiment with how the code above will be presented to the end user.
The right column also includes a clear button that can be used to clear previous answers in case you want the fields to be optional. This way, you can remove accidental selections with the use of a button. The following JavaScript code is executed on click:
document.querySelector('button').addEventListener('click', () => [. document.querySelectorAll('input[type="radio"]')].forEach(input => input.checked = false) >)
Conclusion#
In conclusion, always use a radio group when you need to restrict the number of options to only one. Use checkboxes only when you need to enable users to select multiple options, even if you need to limit the number of selections to a maximum.
Is there anything you think this tutorial is missing? Let us know in the comments below! If you would like to learn more about JavaScript, make sure you check out our roadmap below. Thank you for reading, happy coding! 👨💻
JavaScript Roadmap Learn JavaScript with our guided roadmap This roadmap covers and takes you through the essential concepts in JavaScript, from basic syntax to more advanced concepts like functional and asynchronous programming. Learn More
📚 More Webtips
Level up your skills and master the art of frontend development with bite-sized tutorials.
We don’t spam. Unsubscribe anytime.
- Unlimited access to hundreds of tutorials
- Access to exclusive interactive lessons
- Remove ads to learn without distractions
Recommended
How to Display Key-Value Pairs in React in a Table
How to Rerender Component on Resize in React
How to Easily Fetch and Display JSON in React
Get access to 300+ webtips 💌
Level up your skills and master the art of frontend development with bite-sized tutorials.
We don’t spam. Unsubscribe anytime.
How to select only one checkbox in html
If c01 checked, c02 is unchecked, and vice-versa Solution 1: use Radio button. Solution 1: If you want to ensure that only one item to be selected at once, then actually that’s what radio buttons were invented for (rather than checkboxes).
Html select only one checkbox in a group
// the selector will match all input controls of type :checkbox // and attach a click event handler $("input:checkbox").on('click', function() < // in the handler, 'this' refers to the box clicked on var $box = $(this); if ($box.is(":checked")) < // the name of the box is retrieved using the .attr() method // as it is assumed and expected to be immutable var group = "input:checkbox[name='" + $box.attr("name") + "']"; // the checked state of the group/box on the other hand will change // and the current value is retrieved using .prop() method $(group).prop("checked", false); $box.prop("checked", true); >else < $box.prop("checked", false); >>);
Fruits
Animals
You’d want to bind a change() handler so that the event will fire when the state of a checkbox changes. Then, just deselect all checkboxes apart from the one which triggered the handler:
$('input[type="checkbox"]').on('change', function() < $('input[type="checkbox"]').not(this).prop('checked', false); >);
Here’s a fiddle
As for grouping, if your checkbox «groups» were all siblings:
$('input[type="checkbox"]').on('change', function() < $(this).siblings('input[type="checkbox"]').prop('checked', false); >);
Here’s another fiddle
If your checkboxes are grouped by another attribute, such as name :
$('input[type="checkbox"]').on('change', function() < $('input[name="' + this.name + '"]').not(this).prop('checked', false); >);
Here’s another fiddle
There are already a few answers to this based on pure JS but none of them are quite as concise as I would like them to be.
Here is my solution based on using name tags (as with radio buttons) and a few lines of javascript.
How to check one checkbox only for PHP, In
Select only one checkbox HTML
If you want to ensure that only one item to be selected at once, then actually that’s what radio buttons were invented for (rather than checkboxes). And you don’t need any JS code to make that work.