Search code examples
javascriptformsrequired

get required form elements via DOM in javascript


To do checking on required fields and a custom method of alerting users that required fields are missing, I'm trying to get an array of elements in a form, and have been hunting but not finding a good method.

Is there some variation of

document.getElementById(form).elements;

that would return all the required elements of an array, or a way to test if a given element is required... something akin to either

var my_elements = document.getElementById(form).required_elements;

or

var my_elements = document.getElementById(form).elements;
for (var this_element in my_elements){
    if (this_element.attributes["required"] == "false"){
        my_elements.splice(this_element, 1);
    }
}

Solution

  • Try querySelectorAll with an attribute selector:

    document.getElementById(form).querySelectorAll("[required]")
    

    var requiredElements = document.getElementById("form").querySelectorAll("[required]"),
      c = document.getElementById("check"),
      o = document.getElementById("output");
    
    c.addEventListener("click", function() {
      var s = "";
      for (var i = 0; i < requiredElements.length; i++) {
        var e = requiredElements[i];
        s += e.id + ": " + (e.value.length ? "Filled" : "Not Filled") + "<br>";
      }
      o.innerHTML = s;
    });
    [required] {
      outline: 1px solid red;
    }
    <form id="form">
      <input required type="text" id="text1" />
      <input required type="text" id="text2" />
      <input type="text" id="text3" />
      <input type="text" id="text4" />
      <input required type="text" id="text5" />
    </form>
    
    <br>
    
    <button id="check">Check</button>
    
    <br>
    
    <div id="output">
      Required inputs
    </div>