1

Can someone tell me why this markup/script errors out and doesnt put "Waltdog" into the Hidden1 input field?

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<script>
    document.getElementById("Hidden1").value = 'Waltdog';
</script>
<body>
    <form id="form1" runat="server">
        <div>
            <input id="Hidden1" type="hidden" runat="server" /> 
            Let me know if you see this!!! You crazy Texicans are harshing my Wednesday vibe! :)
        </div>
    </form>
</body>

2 Answers 2

3

Because your script runs before the element exists.

HTML (along with javascript in script tags) in is interpreted top to bottom, therefore when the script runs, the input element has not yet been created.

The solution is either

  • put the script in a function that runs when the page loads
  • put the javascript after the element
Sign up to request clarification or add additional context in comments.

2 Comments

That's right and here is an example of how to achieve the first one: Wrap your code in a function e.g myfunction() and in the HTML write <body onload="myfunction();"> ....
<html xmlns="w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <script> function LoadFunc() { document.getElementById("Hidden1").value = 'Waltdog'; } </script> <body> <form id="form1" runat="server"> <div> <input id="Hidden1" type="hidden" runat="server" /> Let me know if you see this!!! You crazy Texicans are harshing my Wednesday vibe! :) </div> </form> <script>LoadFunc()</script> </body> </html>
0

Put script node below input

<input id="Hidden1" type="hidden" runat="server" /> 
<script>
    document.getElementById("Hidden1").value = 'Waltdog';
</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.