jQuery Validate: make field only required if option is selected [duplicate]

只谈情不闲聊 提交于 2021-02-10 12:10:38

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!