133794m3r
133794m3r

Reputation: 5118

document.forms.length inside function returns 0, outside of function works right

Can anyone explain to me why the following code doesn't work within a function but outside of a function it works perfectly?

function calculate_document_forms_length(){
    document.forms.length;
}

Running it from the console returns "undefined", but when I just run document.forms.length from the console itself returns the number of forms on the page. I've tried to understand why this isn't working but I'm unable to find a reason for it. It happens in firefox, and also chrome. I see no reason why that shouldn't work.

Edit to clarify a few things.

It's ran from the console after the page is done loading. And the following returns the proper value.

document.forms.length;

Thus I don't know why it's acting this way.

OK here's the exact source of the test HTML page.

<html>
  <head>
    <title>test page 01</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <body>
    <form>
        <input type="text" name="test1" />
    </form>
    <form>
        <input type="text" name="tes2" />
    </form>
  </body>
</html>

As you can see no frames, nothing but plain HTML and forms within the tag.

Upvotes: 0

Views: 2675

Answers (3)

cprincec
cprincec

Reputation: 11

The problem is that your code document.forms.length; runs before the whole page is rendered.

To fix this:

  1. Add a defer attribute to your script element OR
  2. Move your script tag towards the end of your html, immediately above the body end tag.

Upvotes: 0

Paperboy
Paperboy

Reputation: 1

This doesn't answer the why but if you return it, it works:

function aa(){
    return document.forms.length;
}

Upvotes: 0

Flambino
Flambino

Reputation: 18773

The function you have there doesn't return anything (i.e. when you run it, it "returns" undefined). Try this instead:

function() {
    return document.forms.length;
}

Also, if you run just that in the console, you'll still get undefined, because you're still not calling the function. You're just creating it, but it's still not being executed.

If you want to run it in the console, you can write

(function() {
    return document.forms.length;
}());

Lastly, if you just write document.forms.length in the console, the console will show you the value, because length is a variable. So that's why that seemed to work.

Upvotes: 2

Related Questions