...

View Full Version : How to put a JavaScript variable into the value of a text box



abell12
03-26-2012, 04:45 PM
I have this code but it doesnt work:


<script type="text/javascript">
var number = 10;
document.getelementbyid(number).value = number;
</script>
<input type="text" id="number" value="">

Can anybody help me out here?

Philip M
03-26-2012, 05:32 PM
A lot of errors in so few lines!

a) You are using the same name/id for a Javascript variable and an HTML element.

b) Javascript is case sensitive so you must spell getElementById exactly as shown

c) The id of the textbox is a literal so must be in quotes. Without the quotes the reference is to the variable number, which has the value of 10, which is nonsense. (Just in case - an id must start with a letter).

d) Your script attempts to refer to the textbox before it exists.


<input type="text" id="mynumber" value="">

<script type="text/javascript">
var number = 10;
document.getElementById("mynumber").value = number;
</script>


Quizmaster: In astronomy, a nucleus, a coma and a tail are parts of which celestial body?
Contestant: A horse.

abell12
03-26-2012, 05:36 PM
Thanks works perfectly.

Sorry about the errors lol.

:thumbsup::thumbsup::thumbsup::thumbsup:

clausrei
03-26-2012, 05:47 PM
There is an error in your syntax . Capital letters are important.



<script type="text/javascript">
var number1 = 10;
var number = document.getElementById("number");
// number.value = "Hello World"; // <-- This does not work jet.
</script>
<input type="text" id="number">


But I could not assign the value jet.

Philip M
03-26-2012, 06:19 PM
clausrei -


Note that in Internet Explorer, names and id's are global variables and thus you should NEVER use a (global) variable or function name which is the same as an HTML element name or id. Example:-


<input id = "text">

<script type = "text/javascript">
text = "Hello World"; // global variable
document.getElementById('text').value = text;
</script>

I agree that the variable here is local because it is declared with the var keyword. But you are playing with fire! Follow my simple rule.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum