开发者

Populate text box with JavaScript on PageLoad

I have a text box开发者_运维技巧 called txtName on my form.

In my page I know I need to place the code in my HEAD tag like so......

<script type='text/javascript' language="javascript">

 document.FormName.txtName.value = "Robert";

 </script> 

But I cant seem to set a value to my textbox txtName with the above code......


That's because your code get executed before the DOM is created. You can do something like this

window.onload = function() { 
  document.forms['FormName'].elements['txtName'].value = "Robert";
}

or use JQuery

$(function() {
  document.forms['FormName'].elements['txtName'].value = "Robert";
  // for a shorter syntax use id
  $('#txtNameId').val("Robert");
}


Your script executed before page loaded. Use onload event


Can you set the id on the textbox? Then you can use getElementByID("textboxid"); Selecting by id is faster.

UPDATE: You need to ensure that the DOM has been load so that your script can locate the element you want to update. One way is:

<body>      
    <form>
    <input id="txtName" name="txtaaaName" type="text" value="notnow"/>
    </form>
    <script type="text/javascript">
        function LoadTextBox(){
            document.getElementById("txtName").value = "ready to go";
        }

        LoadTextBox();
    </script>   
</body> 

An alternative could be where you use onload in the body tag:

<head>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
        <title>Untitled Document</title>
        <script type="text/javascript">
            function LoadTextBox(){
                document.getElementById("txtName").value = "ready to go";
            }
        </script>   
    </head>
    <body onload="LoadTextBox">     
        <form>
        <input id="txtName" name="txtaaaName" type="text" value="notnow"/>
        </form>

    </body> 
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜