Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using jquery validate with multiple fields of the same name

I am trying to get jquery validate to work on multiple fields. Reason being I have dynamically generated fields added and they are simply a list of phone numbers from none to as many as required. A button adds another number.

So I thought I'd put together a basic example and followed the concept from the accepted answer in the following link:

Using JQuery Validate Plugin to validate multiple form fields with identical names

However, it's not doing anything useful. Why is it not working?

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/lib/jquery.delegate.js"></script>
<script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script>


<script>
  $("#submit").click(function(){
    $("field").each(function(){
      $(this).rules("add", {
        required: true,
        email: true,
        messages: {
          required: "Specify a valid email"
        }
      });   
    })
  });


  $(document).ready(function(){
    $("#myform").validate();
  });
</script>

</head>
<body>

<form id="myform">
  <label for="field">Required, email: </label>
  <input class="left" id="field" name="field" />
  <input class="left" id="field" name="field" />
  <input class="left" id="field" name="field" />
  <input class="left" id="field" name="field" />
  <br/>
  <input type="submit" value="Validate!" id="submit" name="submit" />
</form>

</body>
</html>
like image 956
hookenz Avatar asked Apr 07 '10 02:04

hookenz


1 Answers

This: $("field").each(function(){
Should be: $("[name=field]").each(function(){

Also your IDs should be unique, you'll get unpredictable behavior when this isn't true. Also, you should move the rule adding inside the document.ready, like this (this is now all your script):

$(function(){
  $("#myform").validate();
  $("[name=field]").each(function(){
     $(this).rules("add", {
       required: true,
       email: true,
       messages: {
         required: "Specify a valid email"
       }
     });   
   });
});
like image 63
Nick Craver Avatar answered Oct 07 '22 06:10

Nick Craver