开发者

Why are my JavaScript variables not persisting across functions?

I have the following JavaScript in my HTML page referencing an HTML form on the page:

<script type="text/javascript">
<!--

var myForm = document.myForm;

function validateForm() {
    if (myForm.myInput == "")
        alert("Please input some text.");

        return false;
    }

    myForm.submit();
}

function showFormInput() {
    myForm.reset();

    document.getElementById('myInput').style.display = 'inline';
}

//-->
</script>

...

<form name="myForm" id="myForm" action="..." method="post">
    <input id="myInput" name="myInput" type="text" value="" style="display:none;" />
</form>

Both functions are throwing an exception when trying to access the variable myForm, saying that "myForm is null or not an object". Why is this occurring?

UPDATE: One thing I think I'm gathering from this is that global variables should generally be used for st开发者_Python百科ring literals - not elements in the DOM. I"m going to go forward with this, and use element variables sparingly, and only after the DOM has been loaded.


What browser are you using?

IN general you should never use document.* access. This is an MS-IE convention. Instead, use

var myForm = document.getElementById( 'myForm' ) ;
var myInput = document.getElementById( 'myInput' ) ;

if( myInput.value == '' )
{
    // its empty!
}

As outis noted, either put your script block at the bottom of your page, or use the onload event of <body> tag, like this

<script>
function go()
{
    alert( "The DOM has been assembled and can be accessed.. nOW!!!" ) ;
    var myForm = document.getElementById( 'myForm' ) ; // ...
}
</script>
<body onload="go() ;">
</body>


If the sample is representative of the page, the the form "myForm" doesn't exist when the script is evaluated. In addition to using document.getElementById (or document.forms.formName), you'll need to delay setting var myForm until after the form element is processed or, better yet, pass the form as an argument to the functions rather than using a global variable.


Your problem is in document.myForm. You may want to use:

var myForm = document.getElementById('myForm');

UPDATES: The other answers caught another couple of issues:

As bobobobo noted in another answer, you should use document.getElementById() for myForm.myInput as well. In addition outis caught another problem as you should place your <script> block near the end of your HTML document, just before the closing </body> tag. Otherwise your script will execute before the form gets inserted in the DOM.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜