此表单的输入名称相同,但类似(增量)ID。
表格应验证是否有人名,年龄必须是强制性的。
现在只有第一个输入是强制性的。
这是我的代码:
<form id="people">
<div class="section">
<input id="person1" name="person" class="person" type="text" placeholder="First Name" />
<input id="age1" name="age" class="age" type="text" placeholder="Age" />
</div>
<div class="section">
<input id="person2" name="person" class="person" type="text" placeholder="First Name" />
<input id="age2" name="age" class="age" type="text" placeholder="Age" />
</div>
<div class="section">
<input id="person3" name="person" class="person" type="text" placeholder="First Name" />
<input id="age3" name="age" class="age" type="text" placeholder="Age" />
</div>
...
<input type="submit" id="submit" name="submit" value="Add" />
</form>
<script type="text/javascript">
$(function(){
$('#people').validate();
$('#submit').click(function(){
$('[id^="person"]').each(function(){
if ($(this).val().length>0){
//alert($(this).val());
//alert($(this).parent().find('.age').val());
$(this).rules('add', {
required: true,
minlength: 2,
messages: {
required: "Specify the person name",
minlength: "Minimum of 2 characters"
}
});
$(this).parent().find('.age').rules('add', {
required: true,
number: true,
messages: {
required: "Must have an age",
number: "Specify a valid age"
}
});
}
});
});
});
</script>
</body>
答案 0 :(得分:0)
我没有100%的方式,但我认为有几个问题。一个是使用提交点击作为触发器可能会干扰单独调用以验证表单(即验证两次),第二种是输入没有唯一的名称。
更新:
<form id="people" method="post">
<div class="section">
<input id="person1" name="person1" class="person" type="text" placeholder="First Name" />
<input id="age1" name="age1" class="age" type="text" placeholder="Age" />
</div>
<div class="section">
<input id="person2" name="person2" class="person" type="text" placeholder="First Name" />
<input id="age2" name="age2" class="age" type="text" placeholder="Age" />
</div>
<div class="section">
<input id="person3" name="person3" class="person" type="text" placeholder="First Name" />
<input id="age3" name="age3" class="age" type="text" placeholder="Age" />
</div>
<input type="submit" id="submit" name="submit" value="Add" />
</form>
$(function() {
$('#people').validate();
$('.person').blur(function() {
if ($(this).val().length) {
//alert($(this).val());
//alert($(this).parent().find('.age').val());
$(this).rules('add', {
required: true,
minlength: 2,
messages: {
required: "Specify the person name",
minlength: "Minimum of 2 characters"
}
});
$(this).next('input').rules('add', {
required: true,
number: true,
messages: {
required: "Must have an age",
number: "Specify a valid age"
}
});
}
});
});