1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2012
    Rep Power

    Setting value to a text box

    hi guys,

    i want to set a value to a text box using javascript
    i want to use the getElementById function,

    this is what i have so far but its not w0rking, any ideas?

    	<script type = "text/javascript">
    	document.getElementById('fname').value = 'rageedi';
    	//return false;
    <form name="myform" action="javaScriptExample3.html">
    	<input type = "text" name ="firstname" id="fname">
    	<input type = "text" name ="lasttname" id="lname">
    	<input type = "submit" name="submit" value = "submit">
  2. #2
  3. Super Moderator
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jul 2003
    London, UK
    Rep Power
    Your syntax is correct, however you cannot assign a value to an element that does not yet exist. The document loads line by line, so when it reaches your Javascript the input has not yet been created and it will throw an error (Not likely to be seen). You can either move your script below the input element, not something I would personally do, or apply an event listen, as follows.
    Javascript Code:
    onload = startup; // When the document has finished loading, run the "startup" function.
    function startup() {
    	document.getElementById('fname').value = 'rageedi';
    Obviously if you are going to be calling this script from a click or form submission, then it will no longer be an issue.
    [PHP] | [Perl] | [Python] | [Java] != [JavaScript] | [XML] | [C] | [C++] | [LUA] | [MySQL] | [FirebirdSQL] | [PostgreSQL] | [HTML] | [XHTML] | [CSS]

IMN logo majestic logo threadwatch logo seochat tools logo