Retrieving form values in Javascript

Discussion in 'Javascript' started by namanhvu, Sep 29, 2006.

  1. namanhvu

    namanhvu Guest

    Hi everyone,

    I am trying to create a form for authorised users to upload photos to
    an image gallery. I'm attempting to perform simple validation of the
    fields by ensuring the fields aren't empty and that the extensions are
    right. However, I can't seem to access the actual values of the fields
    to start with.

    If I simplify my problem, can anyone tell me why this would work in a
    Javascript alert:

    alert(document.form.Photo1.value);
    //This outputs 'D:/images/x.jpg'

    but this won't:

    var photonumber = "Photo" + 1;
    alert(document.form.photonumber.value);
    // I get "undefined"

    The reason I'm doing this is because I'm looping through a finite set
    of images and need to check each one is valid.

    Is it because I'm not initialising the "photonumber" string correctly?

    If there are any geniuses out there, please help this newbie.

    Thanks in advance!

    Nat.
     
    namanhvu, Sep 29, 2006
    #1
    1. Advertisements

  2. namanhvu

    web.dev Guest

    causing an error is in Internet Explorer. That is because you are
    using a variable name that is the same as the form name. Try a
    different variable name.
     
    web.dev, Sep 29, 2006
    #2
    1. Advertisements

  3. namanhvu

    Lee Guest

    said:
    No, it's becauase the elements of a reference designation in
    that notation are literal values, not variables. If you want
    to use variables, you use a different notation:

    alert(document.form.elements[photonumber].value);


    --
     
    Lee, Sep 29, 2006
    #3
  4. namanhvu

    Randy Webb Guest

    web.dev said the following on 9/28/2006 9:11 PM:
    No, it is because there is no form element named "photonumber", and it
    won't replace the variable with it's value in dot notation. What will
    work however is something like this:

    document.forms['form'].elements[photonumber].value
     
    Randy Webb, Sep 29, 2006
    #4
  5. JRS: In article <>,
    dated Thu, 28 Sep 2006 17:18:30 remote, seen in
    news:comp.lang.javascript, posted :
    One only needs the ability to read the newsgroup FAQ, 2.3, 4.41 & 4.39;
    see below.
     
    Dr John Stockton, Sep 30, 2006
    #5
  6. namanhvu

    namanhvu Guest

    Thanks to everyone who replied.

    I got it to work by doing the following:

    alert(document.form.elements[name].value);

    Nat.
     
    namanhvu, Oct 1, 2006
    #6
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.