Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncheck a checkbox if another checked with javascript

Tags:

javascript

I have two checkbox fields. Using Javascript, I would like to make sure only one checkbox can be ticked. (e.g if one checkbox1 is ticked, if checkbox2 is ticked, checkbox1 will untick)

<input name="fries" type="checkbox" disabled="disabled" id="opt1"/>
<input type="checkbox" name="fries" id="opt2" disabled="disabled"/>

I would also like to have a radio button beneath, if this is clicked, I would like both checkboxes to be unticked.

 <input type="radio" name="o1" id="hotdog" onchange="setFries();"/>

Would the best way to do this be by writing a function, or could I use onclick statements?

like image 511
scott Avatar asked Nov 29 '22 12:11

scott


1 Answers

Well you should use radio buttons, but some people like the look of checkboxes, so this should take care of it. I've added a common class to your inputs:

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/

like image 165
tymeJV Avatar answered Dec 11 '22 11:12

tymeJV