Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Only one selected checkbox

I have 15 check boxes in a form. This checkboxes are independent to eachother. I want a javascript function that makes, when user is selecting 2 checkboxes, the first checked box be unchecked and the second remain checked.

like image 667
Florin Frătică Avatar asked Jul 17 '11 13:07

Florin Frătică


People also ask

How do I make only one checkbox selectable in HTML?

change(function() { $("#myform input:checkbox"). attr("checked", false); $(this). attr("checked", true); }); This should work for any number of checkboxes in the form.

How do I select only one checkbox in react?

If you want to do a selectionable list where only one can be selected the best in term of UX is to use radio button.

How do I enable one checkbox at a time?

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. To modify the default functionality of checkboxes and use like the radio buttons, you need to restrict the user to select multiple checkboxes.


1 Answers

Would you be better off using radio buttons instead of checkboxes as per this site: http://www.echoecho.com/htmlforms10.htm?

If you want to use check boxes I guess you could do something like this:

HTML Code:

<input type="checkbox" id="Check1" value="Value1" onclick="selectOnlyThis(this.id)" /> Option 1
<input type="checkbox" id="Check2" value="Value1" onclick="selectOnlyThis(this.id)" /> Option 2
<input type="checkbox" id="Check3" value="Value1" onclick="selectOnlyThis(this.id)" /> Option 3
<input type="checkbox" id="Check4" value="Value1" onclick="selectOnlyThis(this.id)" /> Option 4

Javascript Code :

function selectOnlyThis(id) {
    for (var i = 1;i <= 4; i++)
    {
        document.getElementById("Check" + i).checked = false;
    }
    document.getElementById(id).checked = true;
}
like image 87
John Avatar answered Oct 09 '22 05:10

John