SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Enthusiast
    Join Date
    Jun 2009
    Posts
    49
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    validate multiple fields that have same name

    Hi

    I am trying to validate the text fields in this form.

    Code:
    <input name="Answer[]" type="text" id="Answer[]" />
                  </label></td>
                </tr>
                <tr>
                  <td>Option2:</td>
                  <td><input name="Answer[]" type="text" id="Answer[]" /></td>
                </tr>
                <tr>
                  <td>Option3:</td>
                  <td><input name="Answer[]" type="text" id="Answer[]" /></td>
                </tr>
                <tr>
                  <td>Option4:</td>
                  <td><input name="Answer[]" type="text" id="Answer[]" /></td>
                </tr>
                <tr>
                  <td>&nbsp;</td>
                  <td><label>
                    <input type="submit" name="Submit" value="Submit" />
    In my head section I have

    Code:
    <SCRIPT LANGUAGE="JavaScript">
    <!-- Begin
    
    function validate() {
    var theMessage = "Please complete the following: \n-----------------------------------\n";
    var noErrors = theMessage
    
    // make sure field is not blank
    for (i = 0; i < document.form1.Answer.length; i++) {
    if (document.form1.Answer[i].value=="")
    theMessage = theMessage + "\n --> You must enter an answer";
    }
    // If no errors, submit the form
    if (theMessage == noErrors) {
    return true;
    } else {
    // If errors were found, show alert message
    alert(theMessage);
    return false;
    }
    }
    // End -->
    </script>
    and on the form I have
    Code:
    onSubmit="return validate(this);"

  2. #2
    SitePoint Wizard bronze trophy
    Join Date
    Jul 2008
    Posts
    5,757
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    theForm.elements will give you an array of the elements. You can loop through it and check the name of each element to see if it has the correct name.

  3. #3
    SitePoint Enthusiast
    Join Date
    Jun 2009
    Posts
    49
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks for the reply.

    I got this working:

    Code:
    <script type="text/javascript">
    
    	function validate(){
    
    		var AnswerInput = document.getElementsByName('Answer[]');
    		for (i=0; i<AnswerInput.length; i++)
    			{
    			 if (AnswerInput[i].value == "")
    				{
    			 	 alert('Complete all the fields');		 
    			 	 return false;
    				}
    			}
    	}
    
    </script>


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •