我有这个表单,输入具有相同的名称,但类似(增量)ID.
我希望表单验证是否有人名,年龄必须是强制性的..
现在发生的是只有第一个输入是强制性的.
这是我的代码:
<html lang="en"> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> <script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script> </head> <body> <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',number: true,messages: { required: "Must have an age",number: "Specify a valid age" } }); } }); }); }); </script> </body>