Jaikrat
Jaikrat

Reputation: 1154

How to skip validating fields in a hidden div

I have one form where I have 5 divs. One is always visible. The other four are kept hidden using style="visibility:hidden; position: absolute;", and can be made visible by calling add method and doing:

.css("visibility","visible")`) 

On-click of some link, and can be removed by calling remove method and doing:

.css("visibility","hidden");`

as well.

Every div has the same number of input fields (i.e. 2 input fields).

But when I submit the page, nothing happens, and when I show my next div (clicking over addNewDiv link), I see both the fields red with one message ("This field is required.") next to those fields.

I tried with style="display:none", but it didn't work, and the below approach also didn't work:

$('#myFormId').validate({ 
        ignore: ":hidden" 
});

I cannot really post the code here.

Upvotes: 0

Views: 8990

Answers (3)

Tim Wilson
Tim Wilson

Reputation: 169

I am thinking that you have html5 required attributes in the form elements that are hidden. Try putting this in where needed and removing the static required attribute. Multipart forms can be tricky on the back end as well. So be sure that you have set up the validation in accordance with the front end.

$('#fieldID').prop('required',true);

Upvotes: 2

Giannis Grivas
Giannis Grivas

Reputation: 3412

This one works fine

<form id="myform">
    <input type="text" name="field1" />
    <br/>
    <input type="text" name="field2" style="display:none;" />
    <br/>
    <input type="submit" />
</form>


$(document).ready(function () {

    $('#myform').validate({
        rules: {
            field1: {
                required: true
            },
            field2: {
                required: true
            }
        },
        submitHandler: function (form) { // for demo
            alert('valid form');
            return false;
        }
    });

});

a {
    display: block;
    position: absolute;
    bottom: 0;
}

Demo is here!

Upvotes: 0

Adrian Forsius
Adrian Forsius

Reputation: 1438

Since semicolon (:) is attribute in jquery and hidden is a CSS rule, you would want to add a class to all hidden fields and then toggle the class instead while adding the class to ignore like so:

$('#myFormId').validate({ 
   ignore: ".hidden" 
});

.hidden
{
    visibility: hidden;
}

Upvotes: 3

Related Questions