JS HTML5 Validate on "display:none" required input elements

13,221

Solution 1

I don't get the same error, in Chrome or Firefox. However I did think that you would need to validate upon clicking "next" which should make it work:

EXAMPLE

HTML

<form action="" method="post" id="form1">
    <div id="div1" style="display:block;">
        <input name="input1" type="text" required />
        <input name="input2" type="text" required />
        <input type="button" value="next" onclick="Next();" />
    </div>
    <div id="div2" style="display:none;">
        <input name="input3" type="text" required />
        <input name="input4" type="text" required />
        <input type="submit" value="submit" />
    </div>
</form>

JS

function Next() {
    var blnNext = true;
    var form = document.getElementById('form1');
    var div = document.getElementById('div1');
    var inputs = div.querySelectorAll('input[type="text"]');
    for (index = 0; index < inputs.length; ++index) {
        if (!inputs[index].validity.valid) {
            blnNext = false;
            form.querySelectorAll('input[type="submit"]')[0].click(); //Force the form to try and submit so we get error messages
        }
    }
    if (blnNext) {
        document.getElementById('div1').style.display = 'none';
        document.getElementById('div2').style.display = 'block';
    }
}

Solution 2

The thing here is that the "required" html attribute is made for inputs which are modifiable by the user.

It doesn't make sense that the browser tells the user that he needs to modify an input which is not visible.

You have to leave the "submit" input for the very end and do your own javascript validations before the user can click the submit input.

Share:
13,221
user3520818
Author by

user3520818

Updated on July 26, 2022

Comments

  • user3520818
    user3520818 almost 2 years

    I have a form which is a multi-div meaning: I fill some fields, then I click next and current div gets to display css proprerty set as "none".

    All the fields in this form are required, below is a snippet of the situation:

    <form action="" method="post">
        <div id="div1" style="display:none">
            <input name="input1" type"text" required />
            <input name="input2" type"text" required />   
        </div>
        <div id="div2" style="display:block">
            <input name="input3" type"text" required />
            <input name="input4" type"text" required />
            <input type"submit" value="submit" />
        </div>
    </form>
    

    Now the problem is that, when I submit the form, if one field of the first div is not filled up, it won't submit and Chrome gives me the following error in the Console

    An invalid form control with name='input1' is not focusable.

    How can I solve this situation? I've thought about catching the error and then showing the first div, but I haven't figured out how to do it.