问题
I use the jQuery Validate plugin and would like to make a select field only required if another select field has a selected option. Here comes my code:
HTML
<form id="my-form">
<input type="text" id="myInput" name="myInput">
<select id="mySelect" name="mySelect">
<option value="">Please select</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
<select id="myOtherSelect" name="myOtherSelect">
<option value="">Please select</option>
<option value="1">Other option 1</option>
<option value="2">Other option 2</option>
<option value="3">Other option 3</option>
</select>
</form>
JAVASCRIPT
$('#my-form').validate({
debug: true,
rules: {
myInput: {
required: true
},
myOtherSelect: {
required: function () {
return $(this).find('[name="mySelect"]').val() != '';
}
}
}});
How do I manage that the select field "my-other-select" is only required when an option has been selected for the field "my-select"?
回答1:
Your code works fine, but as per your comment I think what you are after is
$('#my-form').validate({
debug: true,
rules: {
myInput: {
required: true
},
myOtherSelect: {
required: function (el) {
return $(el).closest('form').find('.mySelect').val() != '';
}
}
}
});
Demo: Fiddle
回答2:
From http://jqueryvalidation.org/validate/ :
$("#myform").validate({
ignore: ".ignore"
});
You can add an class for which validation is ignored, and remove it when the value is selected.
来源:https://stackoverflow.com/questions/30318085/jquery-validate-make-field-only-required-if-option-is-selected