【问题标题】:jQuery Validate: make field only required if option is selected [duplicate]jQuery Validate:仅在选择选项时才需要制作字段[重复]
【发布时间】:2015-05-19 23:07:06
【问题描述】:

我使用 jQuery Validate 插件并希望仅在另一个选择字段具有选定选项时才需要选择字段。这是我的代码:

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() != '';
                            }
                        }
        }});

如何管理选择字段“my-other-select”仅在为“my-select”字段选择选项时才需要?

【问题讨论】:

标签: javascript jquery jquery-validate


【解决方案1】:

您的代码运行良好,但根据您的评论,我认为您所追求的是

$('#my-form').validate({
    debug: true,
    rules: {
        myInput: {
            required: true
        },
        myOtherSelect: {
            required: function (el) {
                return $(el).closest('form').find('.mySelect').val() != '';
            }
        }
    }
});

演示:Fiddle

【讨论】:

【解决方案2】:

来自http://jqueryvalidation.org/validate/

$("#myform").validate({
  ignore: ".ignore"
});

您可以添加一个忽略验证的类,并在选择值时将其删除。

【讨论】:

    猜你喜欢
    • 2021-06-06
    • 1970-01-01
    • 1970-01-01
    • 2016-11-09
    • 1970-01-01
    • 1970-01-01
    • 2011-07-08
    • 1970-01-01
    • 2018-03-08
    相关资源
    最近更新 更多