Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 8 of 8
  1. #1
    Smokes a Lot
    Join Date
    Jul 2003
    Location
    CA, USA
    Posts
    1,594
    Thanks
    5
    Thanked 20 Times in 20 Posts

    Looping through a form

    I've been wondering this for a while but always just go about it a different way so I've never asked the question,

    Say I have the following generic form:

    Code:
    <form>
    	<input type="text" id="fName" name="fName />
    	
    	<select id="state" name="state">
                    <option value="" selected>Select. . .</option>
    		<option value="CA">CA</option>
    		<option value="AZ">AZ</option>
    		<option value="WY">WY</option>
    	</select>
    	
    	<input type="checkbox" id="verify" name="verify" />
    </form>
    Since above I have text input, a select box and a checkbox, if I want to reference each form element I can't just loop through the form elements and check the values or what not because the select box's value and the checkboxes value are irellevent, I actually want the selected index's value and checked respectivly. I usually just put all the form elements into another array "manually" and then loop through that, specifying the info I'm looking for in the array and specify if i=2 see if it's checked.


    Code:
    function formValid()
    {
    	var test=0;
    	var formData=new Array();
    	formData[0]=document.forms[0].state.options[document.forms[0].state.selectedIndex];
    	formData[1]=document.forms[0].fName;
    	formData[2]=document.forms[0].verify;
    	
    	for(i=0;i<formData.length;i++)
    	{
    		if(i==2)
    		{
    			if(!formData[i].checked)
    			{
    				test=1;
                    formData[i].style.backgroundColor='red';
    			}
    		}
    		else if(formData[i].value=="")
    		{
    		    test=1;
                formData[i].style.backgroundColor='red';
    		}
    	}
    			
    	if(test==1)
    	{
    		alert("Fill it all out bub!");
    	}
    }
    Is there a way that this can be accomplised using the pre-existing DOM array of the form elements?

    somthing like but not really:

    Code:
    function isFilled()
    {
      for(i=0;i<document.forms[0].length;i++)
      {
        if(document.forms[0].elements[i].value=="")
        {
          alert("Hey Fill It All Out Buddy!");
        }
      }
    }
    Or is my current procedure best practice. Basically I am asking what is the best \ shortest way to ensure this form is completly filled out.

    Thanks,
    Basscyst
    Last edited by Basscyst; 07-10-2004 at 12:43 AM.
    Helping to build a bigger box. - Adam Matthews

  • #2
    Regular Coder
    Join Date
    Aug 2002
    Location
    USA
    Posts
    625
    Thanks
    0
    Thanked 0 Times in 0 Posts
    <script>
    <!--
    function checkForm(){
    for(i=0;i<myForm.elements.length;i++){
    switch (myForm.elements[i].value){
    case "": alert("You must complete all fields!");
    return false;
    }
    }
    }
    //-->
    </script>





    <form name="myForm">
    <input type="text" id="fName" name="fName" />
    <select id="state" name="state">
    <option value="" selected>Select. . .</option>
    <option value="CA">CA</option>
    <option value="AZ">AZ</option>
    <option value="WY">WY</option>
    </select>
    <input type="checkbox" id="verify" name="verify" />
    <input type="submit" name="sub" value="Submit Form" onClick="javascript:checkForm();return false;" />
    </form>

    <a href="javascript:alert(myForm.state.options.value);">alert</a>


    -james
    "God so loved the world that he gave his only begotten son, so that whosoever believed in him would not perish, but have everlasting life. For God did not send his son into the world to condemn the world, but so that through him the world might be saved. "

  • #3
    Smokes a Lot
    Join Date
    Jul 2003
    Location
    CA, USA
    Posts
    1,594
    Thanks
    5
    Thanked 20 Times in 20 Posts
    Thanks for the attempt but that really doesn't do anything different from my example above. I pondered this over many cigarettes today. I think the way to do it is to loop through each type of form element independently haven't tried it yet, not sure if that can be done. My desired results here is to be able to loop through a form regardless of it's type of elements be them selects, or text and ensure that all fields are filled out, without building my own array, as that can be tedious with larger forms.

    Thanks,
    Basscyst
    Last edited by Basscyst; 07-10-2004 at 06:43 AM.
    Helping to build a bigger box. - Adam Matthews

  • #4
    Banned
    Join Date
    Sep 2003
    Posts
    3,620
    Thanks
    0
    Thanked 0 Times in 0 Posts
    I did not write this but here is a nice little form validator script for you. It validates all form elements, inputs, selects and textareas, also radio button groups and checkboxes:


    Code:
    <html>
    <head>
    <title>Test</title>
    <script type="text/javascript">
    // form validator by Justin Case
    
    function alertField(form, f){
       var fname;
       if(typeof(f) == 'string') fname = f;
       else fname = f.name;
       fname = fname.charAt(0).toUpperCase() + fname.substring(1, fname.length);
       alert('Please enter a value in '+fname);
       if(typeof(f) !== 'string'){
           f.focus();
           return false;
       }
       for(var i = 0; i < form.elements.length; i++){
           if(form.elements[i].name && form.elements[i].name == f){
               form.elements[i].focus();
               return false;
           }
       }
    }
    
    function validateForm(form){
       var radioGroups = new Array();
       for(var i = 0; i < form.elements.length; i++){
           if((form.elements[i].tagName.toLowerCase() == 'select' ||
           form.elements[i].tagName.toLowerCase() == 'textarea' ||
           (form.elements[i].tagName.toLowerCase() == 'input' &&
           (form.elements[i].type.toLowerCase() == 'text' ||
           form.elements[i].type.toLowerCase() == 'file'))) &&
           form.elements[i].className.indexOf('notRequired') < 0 &&
           form.elements[i].value == ''){
               alertField(form, form.elements[i]);
               return false;
           }
           else if(form.elements[i].className.indexOf('checkEmail') >= 0 &&
           form.elements[i].value !== '' &&
           form.elements[i].value.match(/^([\w\-]+\.?)+\@([\w\-]+\.{1})+(com|net|org|edu|int|mil|gov|biz|info|aero|museum|name|coop|\w{2})$/) == null){
               alert('Please enter a valid email address.');
               form.elements[i].focus();
               return false;
           }
           else if(form.elements[i].tagName.toLowerCase() == 'input' &&
           form.elements[i].type.toLowerCase() == 'checkbox' &&
           form.elements[i].className.indexOf('notRequired') < 0 &&
           !form.elements[i].checked){
               alert('You need to agree to our TOS.');
               form.elements[i].focus();
               return false;
           }
           else if(form.elements[i].tagName.toLowerCase() == 'input' &&
           form.elements[i].type.toLowerCase() == 'radio' &&
           !radioGroups[form.elements[i].name] &&
           radioGroups[form.elements[i].name] !== null &&
           form.elements[i].className.indexOf('notRequired') < 0){
               var t = (form.elements[i].checked)? true : null;
               radioGroups[form.elements[i].name] = t;
           }
           else if(form.elements[i].tagName.toLowerCase() == 'input' &&
           form.elements[i].type.toLowerCase() == 'radio' &&
           (radioGroups[form.elements[i].name] ||
           radioGroups[form.elements[i].name] == null) &&
           form.elements[i].className.indexOf('notRequired') < 0){
               if(form.elements[i].checked) radioGroups[form.elements[i].name] = true;
           }
       }
       for(var i in radioGroups){
           if(!radioGroups[i]){
               alertField(form, i);
               return false;
           }
       }
       return true;
    }
    
    </script>
    </head>
    <body>
    
    <form method="post" action="about:blank" onsubmit="return validateForm(this);">
    NAME:  <input type="text" name="name"><br>
    EMAIL: <input type="text" name="email" class="checkEmail"><br>
    SUBJECT: <input type="text" name="subject"><br>
    COMMENT:<br><textarea cols="44" rows="12" name="comments"></textarea><br>
    
    OPINION:<br><input type="radio" name="opinion" value="good"> Good<br>
    <input type="radio" name="opinion" value="ok"> Ok<br>
    <input type="radio" name="opinion" value="bad"> Bad<br><br>
    
    AGREE TO TOS: <input type="checkbox" name="tos"><br><br>
    
    <input type="submit" value="Send">
    <input type="reset" value="Reset">
    </form>
    
    </body>
    </html>
    If some field isn't required, add class="notRequired" to its tag. If it is an email field and you would like the email address validated, add class="checkEmail" to it. If you want both, not required and address check, use class="notRequired checkEmail". Use the notRequired class name on a checkbox if you don't require it checked. If you don't require any value chosen in a radio group, add the notRequired class name to every radio group item.

  • #5
    Smokes a Lot
    Join Date
    Jul 2003
    Location
    CA, USA
    Posts
    1,594
    Thanks
    5
    Thanked 20 Times in 20 Posts
    Thanks Willy that is a very nice script. It also pretty much answers my question, that it is not that easy to just shoot through a form and check different types of elements, this script does just what I was trying to accomplish seems very versatile.

    Thanks Again,

    Basscyst
    Helping to build a bigger box. - Adam Matthews

  • #6
    Banned
    Join Date
    Sep 2003
    Posts
    3,620
    Thanks
    0
    Thanked 0 Times in 0 Posts
    It can be done easier on a form by form basis....
    But that script can be used for darn near any form without any modifications and could also be used as an external script and reused numerous times throughout a site on various pages.....

    .....Willy

  • #7
    Regular Coder
    Join Date
    Aug 2002
    Location
    USA
    Posts
    625
    Thanks
    0
    Thanked 0 Times in 0 Posts
    My desired results here is to be able to loop through a form regardless of it's type of elements be them selects, or text and ensure that all fields are filled out, without building my own array, as that can be tedious with larger forms.


    Sorry, I still don't see what you are trying to do differently...I must be misunderstanding your question.


    -james
    "God so loved the world that he gave his only begotten son, so that whosoever believed in him would not perish, but have everlasting life. For God did not send his son into the world to condemn the world, but so that through him the world might be saved. "

  • #8
    Smokes a Lot
    Join Date
    Jul 2003
    Location
    CA, USA
    Posts
    1,594
    Thanks
    5
    Thanked 20 Times in 20 Posts
    Quote Originally Posted by Willy Duitt
    It can be done easier on a form by form basis....
    But that script can be used for darn near any form without any modifications and could also be used as an external script and reused numerous times throughout a site on various pages.....

    .....Willy

    I understand. My desired end result would have been somthing similar to the code above, probably wouldn't have come out quite as clean though. No sense reinventing it. I was just getting tired of writing basically the same code over and over for each form.

    Thanks,

    Basscyst
    Helping to build a bigger box. - Adam Matthews


  •  

    Posting Permissions

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