user11755091
user11755091

Reputation: 9

How to only check one checkbox in JS?

I have figured out how to create a set of checkboxes but now I am challenged with creating a setting where the user can only choose one of the checkboxes.

I have looked online to try and find some alternative code to try and have found nothing.

            function printChecked(){
                var items=document.getElementsByName('acs');
                var selectedItems="";
                for(var i=0; i<items.length; i++) {
                    if(items[i].type=='checkbox' && items[i].checked)
                        selectedItems+=items[i].value+"\n";

                }

                alert(selectedItems);
            }
        <h1>Select which delimiter you want to use.</h1>
        <big>Select either TSV or CSV: </big><br>
        <input type="checkbox" name="acs" value="CSV">CSV<br> 
        <input type="checkbox" name="acs" value="TSV">TSV<br>
        <p>
            <input type="button" onclick='printChecked()' value="Print Selected Items" /input>
        </p>

You can choose one or the other, both or neither. I want to option to be one or the other.

Upvotes: 0

Views: 443

Answers (3)

Akin Okegbile
Akin Okegbile

Reputation: 1176

Radio boxes will be the better design here.

However, If you insist - you can hack checkboxes into radio box, by adding a listener to the checkboxes

function cbChange(obj) {
    var cbs = document.getElementsByClassName("cb");
    for (var i = 0; i < cbs.length; i++) {
        cbs[i].checked = false;
    }
    obj.checked = true;
}

Demo: http://jsfiddle.net/5uUjj/

Upvotes: 0

ADyson
ADyson

Reputation: 61914

Consider whether you've ever seen this implemented in any website or application you've ever used? No? Can you remember what was used instead?

Use the right tool for the job: radio buttons or a drop down list are probably the most appropriate UI elements to consider when you want the user to choose a single unique value from a list of options.

Checkboxes are appropriate for either a yes/no to a single value, or for specifying multiple options simultaneously.

Most users are familiar with this pattern of use and would probably be confused or frustrated if they came across a checkbox list where they were restricted to a single value - they would be assuming (from universal experience) that they ought to be able to select more than one option.

Upvotes: 1

Emanuele Scarabattoli
Emanuele Scarabattoli

Reputation: 4469

You should use the radio in this case. Why are you trying to use checkbox instead?

Upvotes: 2

Related Questions