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 2 of 2
  1. #1
    New Coder
    Join Date
    Jul 2009
    Location
    Odense, Denmark
    Posts
    72
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Iterating through form with dynamic names

    Hi everybody,


    I have a php file with an almost-standard html form. The not-so-standard part is that the name-attributes of the form elements are dynamically generated as such:

    PHP Code:
    <? for($i=0$i<5$i++) { ?>
    <input type="text" name="field_<? echo $i?>" />
    <? ?>
    Now I want to do some javascript validation on the fields, but I'm having a bit of trouble accessing the values of the fields. My current code is as follows:

    Code:
    var i = 0;
    var num = <? echo $step1_sag_faktura_num; ?>;
    						
    for (i=0; i<num; i++){
    window['file_' + i] = document.forms["nyisagform_step2"]["sag_fak_file_" + i].value;
    }
    But this doesn't seem to work. It gives no error message. It just validates true.

    Can somebody tell me a way to do this? I'm no good at javascript and the code above is pieced together by bit I found on the internet.


    Thanks in advance,
    deafdigit

  • #2
    New Coder
    Join Date
    Nov 2011
    Location
    New England
    Posts
    62
    Thanks
    0
    Thanked 10 Times in 10 Posts
    Does $step1_sag_faktura_num equal 5?


    Your form names are:

    field_1
    field_2
    ...etc

    But in your javascript I see not one reference of "field," just "file". so how are you validating?


    If you want some code to work with, try this:

    PHP Code:
    <? 
    for($i=0$i<5$i++) { 
    ?> 
    <input type="text" name="field_<? echo $i?>" id="field_<? echo $i?>" /> 
    <? ?>
    Code:
    i = 0;
    var num = <? echo $step1_sag_faktura_num; ?>;
    
    for (i=0; i<num; i++){
    window['file_' + i] = document.getElementById('field_' + i).value;
    }
    Last edited by mvmacd; 12-14-2011 at 04:48 PM.
    For programming information, visit irnsystems.com
    Also check out Points2Survey and earn items.


  •  

    Posting Permissions

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