If i have an input like so:
<input type="text" id="textvalue" />
the following code will change its value:
$(document).ready(function() {
$('#textvalue').val("hello");
});
however the following will not work:
$(document).ready(function() {
var = "hello";
$('#textvalue').val(var);
});
Why does the second one not work? I need to be able to change the value of the textbox to the value of a variable
If i have an input like so:
<input type="text" id="textvalue" />
the following code will change its value:
$(document).ready(function() {
$('#textvalue').val("hello");
});
however the following will not work:
$(document).ready(function() {
var = "hello";
$('#textvalue').val(var);
});
Why does the second one not work? I need to be able to change the value of the textbox to the value of a variable
Share Improve this question edited Sep 27, 2011 at 3:31 Loktar 35.3k7 gold badges95 silver badges106 bronze badges asked Mar 16, 2011 at 15:10 geoffs3310geoffs3310 14k24 gold badges67 silver badges85 bronze badges4 Answers
Reset to default 12Your var
statement needs to look something like this
var something = "hello"
$('#textvalue').val(something );
Right now your not actually assigning a value to a variable, and then you are trying to use the var
keyword.
Variable Reference
var
is a reserved word, which means it can't be used as a variable name. If you try:
var variable = "hello";
$('#textvalue').val(variable);
it would work.
Just for interest: var
is used to declare variables, as above.
var is a reserved word in JavaScript because you use it to declare a variable and you are therefore declaring an empty variable.
Use this:
$anything = "hello";
$('#textvalue').val($anything);
Obviously you can replace anything with whatever you want, just don't use var.
Naming conventions are pretty important, you should have a meaningful name for each variable, ideally.
Try this:
$(document).ready(function() {
var myHello = "hello";
$('#textvalue').val(myHello);
});
You have to assign your text to a variable with name. var itself is a keyword.