Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 694
user3520818 Avatar asked Mar 29 '15 12:03

user3520818


2 Answers

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';
    }
}
like image 79
Jamie Barker Avatar answered Nov 15 '22 15:11

Jamie Barker


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.

like image 27
Felixuko Avatar answered Nov 15 '22 13:11

Felixuko