Search code examples
javascripthtmlgetelementbyid

getElementById seems to fail within forms


I have been having problems with getting getElementById working on a specific webpage. So, I've cut it down the following minimal code. In this code, first alert() is displayed, but the second one is not, and about the only thing I can guess why is getElementById() is failing. Any ideas?

<!doctype html>
<html>
    <head>
        <script type="text/javascript">
            function Process(X) {
                alert("In Process at A");
                var y = Document.getElementById("YourName").value;
                alert("At B");
            }
        </script>

        <meta charset="utf-8">
        <title>Test</title>
    </head>

    <body>
        <div>
            <form onsubmit="Process(getElementById('YourName').value);return false;">
                <label for="name">Your name</label>
                <input type="text" maxlength="50" name="YourName" id="YourName">

                <input type="submit" value="Do it" />
            </form> 
        </div>
    </body>
</html>


Solution

  • Document.getElementById fails because getElementById is a property of the document object not the Document object. JS is case-sensitive.

    getElementById('YourName') fails because getElementById is a property of the document object and is not a global.