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

后端 未结 7 2107
说谎
说谎 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 14:56

    Is assigning a class to all required checkbox elements an option? If yes, then this is how I would do it (assuming "class_name" is the name of the css class present in all checkbox elements in question):

    function selectCheckBoxes(bChecked) {
       var aCheckBoxes = YAHOO.util.Dom.getElementsByClassName('class_name', 'input');
       for (var i = 0; i < aCheckBoxes.length; i++) {
          aCheckBoxes[i].checked = bChecked;
       }
    }
    

    If you want to stay away from classes, but can get parent element by ID (or any other method, I will use ID in the example, though), than you can do this:

    function selectCheckBoxes(bChecked) {
       var oParent = document.getElementById('parentsID');
       var aElements = oParent.getElementsByTagName('input');
       for (var i = 0; i < aElements.length; i++) {
          if (aElements[i].type == 'checkbox') {
             aElements[i].checked = bChecked;
          }
       }
    }
    

    I would stick to the "class" method, however.

提交回复
热议问题