Reputation: 9
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
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
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
Reputation: 4469
You should use the radio in this case. Why are you trying to use checkbox instead?
Upvotes: 2