Reputation: 3829
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?
Upvotes: 0
Views: 4233
Reputation: 1677
The jQuery validate plugin by default ignore all hidden elements.
For your case even you set your field to required as Sparky mentioned. Or
simply add ignore: []
to push the plugin to validate all hidden elements in the form.
$form.validate({
ignore: [],
...
Upvotes: 0
Reputation: 98718
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/
Upvotes: 1