gpt4 book ai didi

jQuery 验证器,将任一字段设为必填

转载 作者:行者123 更新时间:2023-12-03 22:40:07 25 4
gpt4 key购买 nike

我试图确保用户输入 2 个字段之一,“ExactOrderSize”或“approxOrderSize”。

<p>Exact size of your order (# of items)</p>
<input id="ExactOrderSize" type="text" name="ExactOrderSize">

<p>Approximate size of your order</p>
<select id="approxOrderSize" name="approxOrderSize" >
<option value="" selected="selected"></option>
<option value="0">0-35</option>
<option value="35">35-50</option>
<option value="50">50-100</option>
</select>

为此,我使用了 jQuery Validator 的帮助。除了这个自定义验证规则之外,一切都运行良好,它似乎没有任何作用。

$('#quoteform').validate({
rules: {
FirstName: {
required: true
},
LastName: {
required: true
},
approxOrderSize: {
required: function() {
if($('#ExactOrderSize').val()=="")
return true;
else
return false;
}
},
DateNeededBy: {
required: true
}
}
});

我的想法是基本上运行一个函数,如果 #ExactOrderSize 字段未填写,则将 #approxOrderSize 字段设为必填字段。又名设置必需= true

到目前为止,我们从 StackOverflow 的答案中发现,问题在于这两个字段可能被隐藏。当页面首次加载时,最初不会显示 #ExactOrderSize 或 #approxOrderSize。

他们必须单击这两个按钮之一才能显示该字段: enter image description here

根据他们选择的按钮,幻灯片动画会显示相应的字段。

"is"--> 显示 #ExactOrderSize 字段

Select Yes, they do know the exact order size

“否”--> 显示#approxOrderSize 字段

Select No, so they can enter in an approximate size

我虽然这将是一个很好的用户界面,但显然它导致了验证消息无法显示的问题,这使得 jQuery 验证无法工作。

作为我尝试过的解决方案:

$('#quoteform').submit(function() {
$('#not-exact').show();
$('#yes-exact').show();
});

这样,所有字段都会在表单提交后显示。但它仍然不起作用。

附注实际页面为HERE如果你想看的话。

最佳答案

I am trying to make sure the user enters 1 of 2 fields

此插件中已经内置了一条名为 require_from_group 的规则,它正是执行此操作。

  1. 包括the additional-methods.js file得到这个规则。

  2. class 添加到这两个字段:ExactOrderSizeapproxOrderSize。类似ordersize

  3. .validate() 方法中声明规则,如下所示...

    rules: {
    ExactOrderSize: {
    require_from_group: [1, '.ordersize']
    },
    approxOrderSize: {
    require_from_group: [1, '.ordersize']
    },
    // your other fields/rules
    },
  4. 使用the groups option以确保这两个字段都只有一条错误消息。

    groups: {
    ordersize: "ExactOrderSize approxOrderSize"
    },
  5. 使用the errorPlacement option将错误消息放置在对这两个字段更有意义的位置。

    errorPlacement: function (error, element) {
    if ($(element).hasClass("ordersize")) {
    error.insertBefore(element.prev('p')); // custom error placement
    } else {
    error.insertAfter(element); // default error placement
    }
    }
  6. 注意:默认情况下,插件将忽略所有隐藏字段。要禁用此功能,只需设置 the ignore option[] 并且什么都不会被忽略。然后,您可以根据一些自定义事件处理程序简单地显示/隐藏输入字段。

工作演示:http://jsfiddle.net/b0qe6Ljg/

关于jQuery 验证器,将任一字段设为必填,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30147589/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com