问题描述
我正在使用jQuery Validate来验证我的表单.问题是我有一个带有多个选择框的表单(动态数字),并且它具有动态名称-> answers[$question['id']]
I'm using jQuery Validate to validate my form. The problem is that I have a form with multiple select boxes (dynamic number) and it has a dynamic name -> answers[$question['id']]
当您有一个固定的名称时,我已经看过一些脚本,您可以使用它来寻址所有输入字段,像这样.
I've seen some scripts when there's a fixed name you can use that to address all the input fields like so.
$('#form').validate({
rules: {
"answers[]" = "required"
}
});
但是在我的示例中这是不可能的,有什么想法吗?谢谢!
But in my example this is not possible, Any ideas? Thanks!
推荐答案
首先,
不是"answers[]" = "required"
它是"answers[]": "required"
注意冒号代替等号.
$('#form').validate({
rules: {
"answers[]": "required"
}
});
第二,这只会将required
规则分配给具有name="answers[]"
的单个字段.
Secondly, that would only assign the required
rule to a single field with name="answers[]"
.
如果要使用name="answers[1]"
,name="answers[2]"
,name="answers[3]"
等轻松地将此规则分配给多个字段,则需要执行以下两项操作之一...
If you want to easily assign this rule to multiple fields with name="answers[1]"
, name="answers[2]"
, name="answers[3]"
, etc., then you'll need to do one of two things...
1)内嵌声明required
规则...
1) Declare the required
rule inline...
使用class
:
<input type="text" name="answers[1]" class="required" />
<input type="text" name="answers[2]" class="required" />
<input type="text" name="answers[3]" class="required" />
使用HTML5或
<input type="text" name="answers[1]" required="required">
<input type="text" name="answers[2]" required="required">
<input type="text" name="answers[3]" required="required">
还有jQuery:
$('#form').validate(); // initialize the plugin
DEMO#1 : http://jsfiddle.net/7JHWf/
2)或使用rules()
方法将规则动态分配给以answers
开头的name
的所有字段:
2) Or assign the rule dynamically using the rules()
method to all fields with a name
starting with answers
:
$('#form').validate(); // initialize the plugin
// assign the rules
$('input[name^="answers"]').each(function() {
$(this).rules('add', {
required: true
});
});
DEMO#2 : http://jsfiddle.net/7JHWf/1/
这篇关于带有多个选择框的jQuery Validate插件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!