Why are my JavaScript variables not persisting across functions?

Posted by Eric Belair on Stack Overflow See other posts from Stack Overflow or by Eric Belair
Published on 2010-05-03T13:09:19Z Indexed on 2010/05/03 13:18 UTC
Read the original article Hit count: 196

Filed under:
|
|
|
|

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?

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about variables