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

    Join Date
    Aug 2012
    Posts
    13
    Rep Power
    0

    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?

    Code:
    <html>
    <head>
    	<script type = "text/javascript">
    	document.getElementById('fname').value = 'rageedi';
    	//return false;
    	</script>
    </head>
    
    
    <body>
    <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">
    </form>
    </body>
    
    </html>
  2. #2
  3. No Profile Picture
    Super Moderator
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jul 2003
    Posts
    4,009
    Rep Power
    2791
    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]

    W3Fools - A W3Schools Intervention.

IMN logo majestic logo threadwatch logo seochat tools logo