0

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?

1
  • Have you tried to solve this yourself yet? If so, where did it go wrong? Commented Aug 10, 2015 at 14:31

2 Answers 2

1

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/

Sign up to request clarification or add additional context in comments.

Comments

0

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: [],
...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.