SitePoint Sponsor

User Tag List

Results 1 to 4 of 4

Hybrid View

  1. #1
    SitePoint Zealot
    Join Date
    Jul 2007
    Posts
    170
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Unhappy Need help array validation

    Hi, I have a form dynamic output by php like this:

    <input name="field[36]" id="field[36]" type="text" size="1" class="textfield" value="2" />
    <input name="field[36]" id="field[36]" type="text" size="1" class="textfield" value="2" />
    <input name="field[80]" id="field[80]" type="text" size="1" class="textfield" value="1" />
    <input name="field[110]" id="field[110]" type="text" size="1" class="textfield" value="1" />
    I'm trying to use javascript to loop through the fields. Is there a way to do it? I can do this php easily:

    while( list( $key, $value ) = each( $_POST['field'] ) )

  2. #2
    ✯✯✯ silver trophybronze trophy php_daemon's Avatar
    Join Date
    Mar 2006
    Posts
    5,284
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Code HTML4Strict:
    <input name="field[]" type="text" size="1" class="textfield" value="2" />
    <input name="field[]" type="text" size="1" class="textfield" value="2" />
    <input name="field[]" type="text" size="1" class="textfield" value="1" />
    <input name="field[]" type="text" size="1" class="textfield" value="1" />
    <input type="button" onclick="checkAll()" />
     
    <script type="text/javascript">
      function checkAll(){
        var fields=document.getElementsByName('field[]');
        for(i=0; fields.length; i++){
            alert(fields[i].value);
        }
      }
    </script>

    This won't work on IE6 though; to make it work on obsolete browsers, you can loop through document.form_name.elements and check for element name.
    Saul

  3. #3
    SitePoint Zealot
    Join Date
    Jul 2007
    Posts
    170
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks daemon, but I can't do this 'field[]', I need the key intact as in field[110]. Is there anyway to do that?

  4. #4
    ✯✯✯ silver trophybronze trophy php_daemon's Avatar
    Join Date
    Mar 2006
    Posts
    5,284
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    OK, I will believe you must specify the indices. Then you could loop through the form elements and use substr to check the first characters of the name.

    Code HTML4Strict:
    <script type="text/javascript">
      function checkAll(){
        var fields=document.myform.elements;
        for(i=0; fields.length; i++){
            if(fields[i].name.substr(0,5)=='field'){
                alert(fields[i].value);
            }
        }
      }
    </script>
    Saul


Bookmarks

Posting Permissions

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