Talon Blackthorne
Talon Blackthorne

Reputation: 27

How do I set the value of an input field via javascript

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>

Upvotes: 1

Views: 145

Answers (2)

Artem Latyshev
Artem Latyshev

Reputation: 595

Put script node below input

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

Upvotes: 0

Jamiec
Jamiec

Reputation: 136074

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

Upvotes: 3

Related Questions