4

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

4 Answers 4

12

Your 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

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, var is a reserved word not a "variable"
7

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.

1 Comment

I see you beat me to it. Promoting yours since it got up there first.
0

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.

1 Comment

This is an JavaScript anti pattern. Without var keyword you are creating global variable and thus polluting global namespace.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.