Revalidate an element when changed programmatically with javascript

javascript, jquery, jquery-validate

Solution

You can programatically trigger a validation test using the `.valid()` method. You can attach `.valid()` to a single input element or to the whole form.

$('#myform').valid();

or

$('input[name="fieldName"]').valid();

Calling `.valid()` will immediately trigger a validation test on the selected element(s) as well as returning a boolean value.

(Note: `validate()` needs to be called on the form before checking it using this method.)

See: http://jqueryvalidation.org/valid/

Problem

I am using JQuery Validate plugin, and validating inputs this way. An input has been marked as invalid, after submitting form once. There is a field, "from", whose value is linked to another field, "to". How do I get the field "to" to revalidate once "from" has been changed? HTML: ``` <div id="fromPanel" class="inputPanel"> <label>From</label> <div class="invalid valid" generated="true" for="from"></div> <select id="from" class="campusChooser valid" required="required" name="from"> <option value="" disabled="disabled"> -- Choose a Campus -- </option> <option selected="selected" value="UTSG">St. George</option> <option value="UTM">Mississauga</option> </select> </div> <div id="toPanel" class="inputPanel"> <label>To</label> <div class="invalid" generated="true" for="to"></div> <select id="to" class="campusChooser" required="required" name="to"> <option value="" disabled="disabled"> -- Choose a Campus -- </option> <option value="UTSG">St. George</option> <option selected="selected" value="UTM">Mississauga</option> </select> </div> ``` JS: ``` $(function () { $("#to").change(function() { var otherField = field == "to" ? "from" : "to", otherValue; if (value == "UTSG") { otherValue = "UTM"; } else if (value == "UTM") { otherValue = "UTSG"; } else { otherValue = ""; } $("#" + otherField).find("option[value='{0}']".format(otherValue)).prop("selected", true); }); }); ```

Original source