Thread: Javascript simple question

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Jun 2011
    Posts
    12

    Javascript simple question

    Sorry I know this place is mainly for C. But I don't really want to have to register to another site for this JS question. (I'm sure a lot of you have dealt with websites anyway )

    This question is pretty simple, but I just can't figure out why the FOR loop breaks. To me it seems like a bug. It simply breaks after 1 iteration.

    I created a dummie page, for you to see. Simply save it as a .html and run it

    Code:
    <html><head><script type="text/javascript">
    
    function validateForm()
    {
    
    var fields = new Array;
    var fields =[
    document.getElementById("one"),
    document.getElementById("two"),
    document.getElementById("three")];
    
      for (var i = 0; i < parseInt(fields.length); i++) {
        alert(i);
    
        if ( fields[i].value == "" ) {
          alert("Field" + (i+1) + " has no value");   
        }
     
      }
    
    }
    </script></head><body>
    
    <form name="form1">
    Field 1 enter: <input type="text" id="one"> <br />
    Field 2 enter: <input type="text" name="two"> <br />
    Field 3 etner: <input type="text" name="three"> <br /><br />
    
    <input type="button" onclick="validateForm()" value="Submit" />
    
    </form></body></html>
    The error occurs on fields[i].value .. The error is the var i
    You see, if you replace i with 0: fields[0].value, it will successfully loop 3 times.
    I just don't understand why using that variable, fails?

    I tried so many things, moving the script to bottom of page, converting value of i to a char, etc. I may of missed something, but if you take a quick look maybe you know this problem. (I know I can resort to doing multiple IF statement, I just want to know why this logical loop doesn't work)
    Last edited by astral; 07-03-2011 at 05:06 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Simple JavaScript Code Issue
    By clegs in forum Tech Board
    Replies: 8
    Last Post: 07-14-2008, 03:11 AM
  2. Question about JavaScript
    By Flakster in forum Tech Board
    Replies: 6
    Last Post: 06-10-2005, 09:37 AM
  3. JavaScript question
    By Magos in forum A Brief History of Cprogramming.com
    Replies: 9
    Last Post: 09-08-2002, 01:46 PM
  4. Javascript Question!!!
    By compjinx in forum A Brief History of Cprogramming.com
    Replies: 7
    Last Post: 02-02-2002, 06:10 PM
  5. Javascript Question!!!
    By compjinx in forum C# Programming
    Replies: 2
    Last Post: 01-30-2002, 01:33 PM

Tags for this Thread