tags:

views:

63

answers:

3

Why does this code alert three undefined values?

    <html>
        <head>
            <script type="text/javascript" language="javascript">
            function doIt(form){
                alert(form.elements.length)
                for (var i in form.elements){
                    alert(form.elements[i].value);
                }
            }
            </script>
        </head>
        <body id="body">
            <form method="GET" action="http://localhost/sandbox/moving/controllers/companies/cSubmit_bid.php"&gt;
               <input type="button" value="Go" onclick="doIt(this.form)">
            </form>
        </body>
    </html>

Thank you in advance.

+1  A: 

Update:

Since you have just one input field, the below code will show just for that, that is button.

Here is the working demo

You could modify your function and it's call this way:

    <input type="button" value="Go" onclick="doIt()">

    function doIt(){
        var form = document.forms[0]; // get first form or adjust accordingly
        for (var i = 0; i < form.elements.length; i++){
            alert(form.elements[i].value);
        }
    }
Sarfraz
"this" is the reference to the button, not the form.
HoLyVieR
I am referencing the form object form the button. Is that whats making me get three undefined values? The undefined problem still exists even after trying your answer.
Babiker
@Babiker: See my updated answer please.
Sarfraz
@sAc i am still getting three undefined alerts.
Babiker
It is on a button, it's just all on the same line.
jasongetsdown
@jasongetsdown: Yes my answer is updated for that :)
Sarfraz
@sAc , @jasongetsdown, @HolyVieR is anyone getting the alerts after running this code?
Babiker
@Babiker: I have updated my answer with working demo, please check :)
Sarfraz
+3  A: 

You've having a problem because the array in form.elements isn't a true array. its a HTMLCollection which is an array-like object. As a result it isn't iterable with a for...in loop. Switch to a standard for loop and it works as expected.

The for...in loop is really meant for iterating through the properties of an object. It is not recommended for use on arrays (see the description section here).

jasongetsdown
+2  A: 

form.elements is an array-like structure which has three properties: length, item, namedItem. Hence with for-in loop, you are getting three alerts for each of these properties. A regular for loop would work correctly

Marimuthu Madasamy