最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery .val() not working when setting a variable - Stack Overflow

programmeradmin3浏览0评论

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 badges
Add a comment  | 

4 Answers 4

Reset to default 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

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.

发布评论

评论列表(0)

  1. 暂无评论