简体   繁体   中英

How to write a variable to an input field with javaScript/jQuery?

I have input box #bar inside of div #foo. The value of input box #bar is "bar"

<div id="foo">
    <input id="bar" type="text" name="bar" size="5" value="bar" style="width:200px"/>
</div>

I want to use jQuery to change the value of #bar from "bar" to "foobar".

I saw this question on stackoverflow: Insert javascript (jquery) variable in html input field (textbox)

and tried the below jQuery:

$(document).ready(function() {
    var fooBar = "foobar";
    $('#bar').val(data[0].fooBar);
});

I must be missing something. I tried searching google, but as the post above mentions it was not very helpful. here is a link to the fiddle.

There is no variable called data , you have a variable called fooBar just use it

$(document).ready(function() {
    var fooBar = "foobar";
    $('#bar').val(fooBar);
});

Demo: Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM