jQuery Validate:仅在选择了选项的情况下才需要使字段 [英] jQuery Validate: make field only required if option is selected

查看:58
本文介绍了jQuery Validate:仅在选择了选项的情况下才需要使字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用jQuery Validate插件,并且仅在另一个选择字段具有选定选项的情况下才想使选择字段成为必需.这是我的代码:

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"?

推荐答案

您的代码可以正常工作,但是根据您的评论,我认为您追求的是

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

演示:小提琴

这篇关于jQuery Validate:仅在选择了选项的情况下才需要使字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆