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 3 of 3
  1. #1
    New Coder
    Join Date
    Mar 2003
    Posts
    64
    Thanks
    0
    Thanked 0 Times in 0 Posts

    array in form vaidation

    Given:

    <script>
    str = "username,password,newsletter";
    var a = str.split(",");
    function show(){
    if(!document.reg.a[0].value){
    alert(document.reg.a[0].value);
    return false;
    }
    return true
    }
    </script>

    <form name="reg">
    username <input type="text" name="username">
    <input type="submit" name="submit" value="submit" onclick="return validate()">
    </form>

    An alert should popup with the word "username" on it. However, this just submits and no alert. It's actually "document.reg.a[0].value" that doesn't evaluate to anything and a[0] is 'username'. I want for it to alert and the form not to submit if username is blank. solutions? Thanks.

  • #2
    Senior Coder
    Join Date
    Aug 2002
    Posts
    3,467
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Think about it for a sec, if document.reg.username referes to the username field, then document.reg.a[0] tries to refer to the first a field. Since your form has no a field(s), you get an error.

    You must use the elements collection here.
    Code:
    document.reg.elements[a[0]].value
    The elements collection + lookup operator (also called the hashtable) must receive a string. Since accessing a[0] returns 'username', then the above is essentially the same as
    Code:
    document.reg.elements['username']
    Which i also the same as
    Code:
    document.reg.username
    There you go!
    My Site | fValidate | My Brainbench | MSDN | Gecko | xBrowser DOM | PHP | Ars | PVP
    “Minds are like parachutes. They don't work unless they are open”
    “Maturity is simply knowing when to not be immature”

  • #3
    New Coder
    Join Date
    Mar 2003
    Posts
    64
    Thanks
    0
    Thanked 0 Times in 0 Posts
    ah ha! thanks!


  •  

    Posting Permissions

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