javascripthtmlcss

How to handle required fields in display:"none"


I have display:none element, that contains required inputs. When I submit form it must focus on required fields, but as they are not displayed Im not able to do it. What I want is to make this element display:block and then focus on the input when there validation error ocured.

This is how my code looks like:

<form>

<div style="display: none">
    <input required></input>
</div>

<button type="submit">
</form>

Solution

  • You can achieve this by first calling checkValidity() of the Form.

    If that reports that the Form is not valid, then gather the invalid elements using .querySelectorAll(':invalid') and then reveal those elements - or in this case, their parent divs.

    Demo:

    function submitClick() {
      var theForm = document.getElementById('myForm');
    
      if (theForm.checkValidity()) {
        console.log("All elements are valid");
        return true; // Allow submit to proceed
      }
    
      var invalidItems = theForm.querySelectorAll(':invalid');
    
      for (var item of invalidItems) {
        console.log("Element " + item.name + " is not valid");
        item.parentNode.setAttribute("style", "display: block;")
      }
      return false; // Do not allow submit to proceed
    }
    <form id="myForm" onsubmit="alert('Form will be submitted')">
    
      <div style="display: none">
        Required field 1 (empty)<input name="v1" required value="" />
      </div>
    
      <div style="display: none">
        Required field 2 (Hello)<input name="v2" required value="Hello" />
      </div>
    
      <button type="submit" onclick="return submitClick();">Submit form</button>
    </form>