#1
  1. No Profile Picture
    Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2004
    Posts
    2
    Rep Power
    0

    dynamic JS form validation


    Looking for help with JS form validation. I have a form with multiple select boxes. The number of select boxes is dynamic. It can be anywhere from 0 to 15 select boxes, depending on some previous values input by the user. The box, if it exists, has a name such as Box1, Box2, Box3...

    I would like to validate that the select box is filled out by the user. How do I execute the validation when the number of select boxes to be validated is changing?

    Thanks.
  2. #2
  3. Procrastinator Extraordinaire
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2003
    Location
    Sydney, Australia
    Posts
    240
    Rep Power
    16
    Simple fix, use the eval function.

    Code:
    function checkForm(numberOfBoxes) {
    var boxFunction="document.formName.Box"; // Store the box function in a variable
    var errors=0; // set the errors to 0
    
    // check every box to make sure it doesnt hold an empty value
    var i=0;
    while(i<numberOfBoxes) {
    var boxFunction+=i;
    var boxFunction=eval(boxFunction);
       if(boxFunction.value=="") {
         errors=1;
       }
    }
    
    // If there are no errors submit, otherwise display an error
    if(errors == 0) {
    document.formName.submit();
    }
    else {
    alert("You did not fill out the form correctly!");
    }
    }
    Of course you will need to change "formName" to reflect the actual name of your form.

    To make the function activate you would use this as a submit button:
    Code:
    <input type="button" value="submit" onClick="checkForm(3);">
    Its quite simple to change checkForms parameter to match the ammount of box elements present. Hope this works for ya.
    Last edited by m4dm4n; January 7th, 2004 at 11:09 PM.
  4. #3
  5. No Profile Picture
    Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2004
    Posts
    2
    Rep Power
    0
    Thanks m4dm4n, the eval function worked as advertised. I was missing that and the passing of the number of boxes. Once I saw your sample code, all was solved.

IMN logo majestic logo threadwatch logo seochat tools logo