Using JavaScript to manipulate HTML input (checkbox) elements via type instead of name

后端 未结 7 2099
说谎
说谎 2021-01-04 14:41

I am implementing an HTML form with some checkbox input elements, and I want to have a Select All or DeSelect All button. However, I do not want to rely on the name

7条回答
  •  独厮守ぢ
    2021-01-04 15:01

    iterate through the form.elements collection and check .type == "checkbox".

    var button = getSelectAllButtonInFormSomeHow();
    /*all formelements have a reference to the form. And the form has an elements-collection.*/
    var elements = button.form.elements;
    
    for(var i = 0; i < elements.length;i++) {
        var input = elements[i];
        if (input.tagName == "input" && input.type == "checkbox") input.checked = true;
    }
    

提交回复
热议问题