make checkbox behave like radio buttons with javascript

前端 未结 11 743
迷失自我
迷失自我 2020-11-28 06:28

I need to manipulate the behavior of the check boxes with javascript. They should basically behave like radio buttons (only one selectable at a time, plus unselect any previ

11条回答
  •  隐瞒了意图╮
    2020-11-28 07:10

    try this

    and this is the javascript

    (function () {
        function checkLikeRadio(tag) {
            var form = document.getElementById(tag);//selecting the form ID 
            var checkboxList = form.getElementsByTagName("input");//selecting all checkbox of that form who will behave like radio button
            for (var i = 0; i < checkboxList.length; i++) {//loop thorough every checkbox and set there value false. 
                if (checkboxList[i].type == "checkbox") {
                    checkboxList[i].checked = false;
                }
                checkboxList[i].onclick = function () {
                    checkLikeRadio(tag);//recursively calling the same function again to uncheck all checkbox
                    checkBoxName(this);// passing the location of selected checkbox to another function. 
                };
            }
        }
    
        function checkBoxName(id) {
            return id.checked = true;// selecting the selected checkbox and maiking its value true; 
        }
        window.onload = function () {
            checkLikeRadio("form");
        };
    })();
    

提交回复
热议问题