I have a form that I am validating on the client-side using the jQuery Validation plugin. For brevity I have created a simple test case showing my issue. The form has a single text input field and a single hidden input field.
<script>
function testThis() {
alert('value before: ' + $("#testhidden").val());
$("#testhidden").val("sometext");
alert('value after: ' + $("#testhidden").val());
}
</script>
<form name="testform" id="testform" method="post" action="">
Enter Text: <input type="text" id="testfield" title="test field is required" name="testfield" size="20" minlength="2" maxlength="10" required="required" />
<input type="hidden" id="testhidden" title="hidden field is required" name="testhidden" minlength="4" required="required" />
<p><input type="button" id="addvalue" name="addvalue" value="Add Value via JavaScript" onclick="testThis();" /></p>
<p><input type="submit" id="testbutton" name="testbutton" value="Submit Form" /></p>
</form>
Validation for both fields are that they are required and must be of a certain length; at least 4 characters for the hidden field and 2-10 characters for the text field. My caveat is that the hidden field is being updated via JavaScript after the form has been loaded to the DOM.
I have created a fiddle to demonstrate my problem. For this test I have added a button to simulate how I am modifying the hidden input's value via JavaScript. To test do this:
- Try to submit the form without entering any text. You should get 2 validation errors.
- Next enter text into the text input field and after entering at least 2 characters the first validation message should be hidden.
- If you try to submit at this point it still will not because of the hidden field requirement.
- Next click the Add value via JavaScript button. I am alerting the before and after values. At this point, once the hidden field has the correct data, I would like the validation message to be hidden but it is not.
- At this point the form will submit because the validation criteria has been met but the error message is still displayed.
How can I get the validation message to hide once the hidden field contains the appropriate text?
Here is the simple validation call that I am using to go along with the test form above:
$("#testform").validate({errorElement:"div",ignore:[]});
In case it matters I am using jQuery 1.11.1 and jQuery Validate 1.12.0
Update
Although Pointy's answer does not solve the issue I think he is headed down the right path. I need some way to trigger the validation to fire after updating the hidden field. I have updated my fiddle now by adding a second input text field. I am also updating this input field via JavaScript. When I trigger the blur() event on this new field after updating via JavaScript it correctly hides the validation message. Doing the same thing on the hidden field however still does not work. It definitely has something to do with it being a hidden field...