www.webdeveloper.com
Results 1 to 4 of 4

Thread: Passing array values to form fields

  1. #1
    Join Date
    Apr 2012
    Posts
    2

    Passing array values to form fields

    I'm far from an expert at JavaScript as you're about to see.

    I'm trying to pass an array of values to a series of html form fields.

    the data in the array is in the variables dirLen[]

    the form fields I'm trying to populate are named
    dirLen1
    dirLen2
    dirLen3
    etc...

    I can pass individual array values to the individual form fields using:
    form.field_name.value=arrayValue
    so I know my array is good and that the above syntax works.

    I just don't know the format to call the form field in the following for-loop.

    // for-loop to populate form fields
    for (var k=0;k<=23;k++)
    {
    form.dirLen[k].value=dirLen[k];
    }

    I've tried:
    form.['dirLen'+k].value=dirLen[k]
    form."dirLen"+[k].value=dirLen[k]
    form.[dirLen+k].value=dirLen[k]
    form.["dirLen"+k].value=dirLen[k]

    and lots of others. Any help is appreciated.

    -Ryan

  2. #2
    Join Date
    Dec 2011
    Location
    Centurion, South Africa
    Posts
    795
    Did you try this one:

    Code:
    form['dirLen' + k].value = dirLen[k];

  3. #3
    Join Date
    Nov 2010
    Posts
    1,097
    it's quite possible that you are referencing your form incorrectly. If you are just working with named fields (ie, no id's), easiest is to name your form.

    you will also want to remove the dot between the form reference and the first square bracket, and also bear in mind that you are starting your loop off at 0 but your field names start at 1:

    Code:
    <!DOCTYPE html>
     <html>
     <head>
     </head>
     <body>
    <form name="myform">
    <input type="text" name="dirLen1"/>
    <input type="text" name="dirLen2"/>
    <input type="text" name="dirLen3"/>
    </form>
    <script type = "text/javascript">
    var dirLen=[5,7,9]
    for(var k=0;k<dirLen.length;k++){
    document.myform["dirLen"+(k+1)].value=dirLen[k]
    }
    </script>
     </body>
     </html>

  4. #4
    Join Date
    Apr 2012
    Posts
    2
    bioniod: thanks, just what I was looking for. Worked perfectly.

    xelawho: I still have some tweeking to do on the incrementing k+1 vs K etc. but needed to get over this hurdle first.

    This is my first post here and I got a solution in a couple of hours. Awesome.

    thanks.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

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



Recent Articles