JQuery 验证:如何检查多个选择中的项目
我有一个使用 JQuery 验证插件的表单。
<label>
<input name="Distribution[]" type="checkbox" id="dist_europe" class="required minlength:1" value="Europe" /> Europe
</label>
<select name="Europe[]" size="5" multiple id="Europe">
<option value='Albania'>Albania</option>
<option value='Andorra'>Andorra</option>
<option value='Austria'>Austria</option>
</select>
我需要进行“条件”验证。 例如。如果选中复选框,请确保“选择选项已选中”中至少一项。
$(document).ready(function(){
$("#commentForm").validate({
rules: {
Europe: {
required: "#dist_europe:checked",
minlength: 1
}
},
messages: {
Europe: "Please select at least 1 country"
}
}
})
我现在面临的问题是:
- 我能够检测到该复选框已被选中。
- 但是,我无法检查“选择”数组 Europe[]
- 如果我删除该数组并将其命名为 Europe,我将能够检测到至少选择了一项。但是,这样做将意味着后端 PHP 脚本将无法处理数组中的多重选择。
我该如何解决这个问题?谢谢
I have a form using JQuery validation plugin.
<label>
<input name="Distribution[]" type="checkbox" id="dist_europe" class="required minlength:1" value="Europe" /> Europe
</label>
<select name="Europe[]" size="5" multiple id="Europe">
<option value='Albania'>Albania</option>
<option value='Andorra'>Andorra</option>
<option value='Austria'>Austria</option>
</select>
I need to do 'conditional' validation.
eg. If checkbox is selected, make sure at least one item in 'select option is selected'.
$(document).ready(function(){
$("#commentForm").validate({
rules: {
Europe: {
required: "#dist_europe:checked",
minlength: 1
}
},
messages: {
Europe: "Please select at least 1 country"
}
}
})
The issue I am facing now is :
- I am able to detect that the checkbox is selected.
- However, I am not able to check the 'select' array, Europe[]
- If I remove the array, and name it Europe, I will be able to detect that at least one item is selected. But, doing that will mean the backend PHP script will not be able to process the multiple select in the array.
How do I work around this? Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用
name="Europe[]"
之类的名称时,您需要使用字符串作为标识符(标识符是名称,而不是元素的 id)在rules
和messages
中,如下所示:您可以在此处进行测试。
When using a name like
name="Europe[]"
, you'll need to use a string for your identifier (the identifier is the name, not the id of the element) inrules
andmessages
, like this:You can test it out here.