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.
The function you have there doesn’t return anything (i.e. when you run it, it “returns”
undefined). Try this instead: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
Lastly, if you just write
document.forms.lengthin the console, the console will show you the value, becauselengthis a variable. So that’s why that seemed to work.