Uncheck a checkbox if another checked with javascript

后端 未结 5 1073
北恋
北恋 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:24

    Also based on tymeJV's answer above, if you want to only deactivate the other checkbox when one is clicked you can do this:

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

    tymeJV's function does not let you have both unticked - this does. (yes, weird but true.. sometimes there's a semantic reason why you want two tickboxes not radio buttons)

提交回复
热议问题