Gags Gags - 4 months ago 73
jQuery Question

Validate onchange input fields jQuery Validate plugin

There is a scenario where we have a dropdown to choose from values and also

other
option to specify value in a text input field.

Whenever,
other
option is chosen, a text field is displayed and then I want it to be validated.

select
is:

<select class="form-control" name="amount_sch" id="amount_sch">
<option value="" selected>Please Select</option>
<option value="1000">1000</option>
<option value="2000">2000</option>
<option value="othr_amt">Other, Please Specify</option>
</select>


input
is:

<input type="text" id="amount_sch_other" name="amount_sch_other"
class="form-control no-extras" placeholder="Enter Amount"
style="display:none;"/>


JQuery to show/hide:

$("#amount_sch").change(function() {
if ( $(this).val() == "othr_amt") {
$("#amount_sch_other").show();
}
else{
$("#amount_sch_other").hide();
}
});


rules
option within
.validate()
...

amount_sch : {
required : true,
}


With this, only
select
is validated, but how can I validate
text
field when it is visible?

Answer

By default, the jQuery Validate plugin will dynamically ignore validation for any field that is hidden. So you simply need to declare validation rules for the text box and let the plugin automatically do its thing.

rules: {
    amount_sch: {
        required: true,
    },
    amount_sch_other: {
        required: true,
    }
}

Whenever the text field shown, it will be validated; and when it's hidden, it will not be validated.

DEMO: http://jsfiddle.net/Lcdexmwc/

Comments