HelloWorld
HelloWorld

Reputation: 2330

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.

Upvotes: 0

Views: 186

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

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

Upvotes: 1

Related Questions