How can I select all checkboxes from a form using pure JavaScript (without JS frameworks)?

前端 未结 2 1591
悲&欢浪女
悲&欢浪女 2020-12-06 00:39

I have question, how write function to select all chceckbox on form, when all checkbox Id start from some const. string, using pure java script (without jquery

相关标签:
2条回答
  • 2020-12-06 01:07

    You could use getElementsByTagName to get all the input elements:

    var inputs = document.getElementsByTagName("input");
    for(var i = 0; i < inputs.length; i++) {
        if(inputs[i].type == "checkbox") {
            inputs[i].checked = true; 
        }  
    }
    

    Here's an example of that. If you only care about newer browsers, you could use querySelectorAll:

    var inputs = document.querySelectorAll("input[type='checkbox']");
    for(var i = 0; i < inputs.length; i++) {
        inputs[i].checked = true;   
    }
    

    And an example of that one. As an aside, you mentioned in your question that when using jQuery you could do this using each. You don't need to use each, as most jQuery methods operate on all elements in the matched set, so you can do it in just one line:

    $("input[type='checkbox']").prop("checked", true);
    
    0 讨论(0)
  • 2020-12-06 01:13

    In your case:

    for (i = 1; i<3; i++) {
      document.getElementById('lang_'+i).checked = true;
    }
    
    0 讨论(0)
提交回复
热议问题