Uncheck a checkbox if another checked with javascript

后端 未结 5 1080
北恋
北恋 2020-12-21 09:48

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 w

5条回答
  •  抹茶落季
    2020-12-21 10:23

    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/

提交回复
热议问题