Eric Mat
Eric Mat

Reputation: 9

How to select only one checkbox from many checkboxes with Javascript or jquery?

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

Answers (3)

Sai Pravesh
Sai Pravesh

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

Mert Çelik
Mert Çelik

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

Moawaz Ayub
Moawaz Ayub

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

Related Questions