Reputation: 9
There are several checkboxes in html form. And I need the user to be allowed to select only one checkbox. For example: when clicked on the second checkbox, a message will be displayed that deactivates the previous checkbox.
Upvotes: 0
Views: 2944
Reputation: 175
To answer your question, you can disable/enable a checkbox via JavaScript using
document.querySelector('#your-selector').disabled=true
document.querySelector('#your-selector').disabled=false
You can check/uncheck a checkbox using
document.querySelector('#your-selector').checked=true
document.querySelector('#your-selector').checked=false
So you need to add a condition when to disable/enable or check/uncheck it based on your need.
That said as stated by others use of radio button is the suggested approach to your requirement.
Upvotes: 0
Reputation: 382
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()
}
})
})
<div>
<input class="cgroup" type="checkbox">
<input class="cgroup" type="checkbox">
<input class="cgroup" type="checkbox">
<input class="cgroup" type="checkbox">
</div>
Upvotes: 1
Reputation: 66
You can use a Radio button instead of a checkbox that will only allow a user to select one at a time. but for disabling you would have to write some javascript code after selection.
Upvotes: 1