Reputation: 23
From what I understand radios might be the best option, but I need to use checkboxes. I saw a similar question here: Uncheck a checkbox if another checked with javascript except, I want the user to be able to select one box or the other using only the two checkboxes, but also be able to deselect whichever box is checked if they decide they no longer want either box checked and not have to use a radio like in the example.
Here is the example:
<input class="cb" name="fries" type="checkbox" id="opt1" onchange="cbChange(this)"/>
<input class="cb" type="checkbox" name="fries" id="opt2" onchange="cbChange(this)"/>
<input class="cb" type="radio" name="o1" id="hotdog" onchange="cbChange(this)"/>
and here is the code they used, but with this I don't have the option to deselect both checkboxes unless I use the radio:
function cbChange(obj) {
var cbs = document.getElementsByClassName("cb");
for (var i = 0; i < cbs.length; i++) {
cbs[i].checked = false;
}
obj.checked = true;
}
Upvotes: 0
Views: 129
Reputation: 171411
JavaScript:
function cbChange(obj)
{
if (obj.checked) {
var cbs = document.getElementsByClassName("cb");
for (var i = 0; i < cbs.length; i++)
cbs[i].checked = false;
obj.checked = true;
}
}
HTML:
<input class="cb" name="fries" type="checkbox" id="opt1" onchange="cbChange(this)"/>
<input class="cb" name="fries" type="checkbox" id="opt2" onchange="cbChange(this)"/>
Upvotes: 1