Question

I want to add the text from a text field onto another div's style attribute.

For example, there is an input on the page:

<input id="text" />

and a div on the page:

<div id="div1" stlye="background:"></div>

I want what the user inputs in the text_field to show in that div's style. So if a user types the string #FF0000, then I want (in realtime) for the div's style attribute to change to

<div id="div1" style="background:#FF0000"></div>

How can I accomplish this with JavaScript

Was it helpful?

Solution

$('#text').keyup(function () {
    $("#div1").css('background', $('#text').val());
});

OTHER TIPS

Use the change() function like so

$('#inp').keyup(function () {
$("#div1").css('background', $('#inp').val());
});   

with keyup

http://jsfiddle.net/NVW4S/1/

with change http://jsfiddle.net/NVW4S/

I recommend using the jQuery on function:

$('#text').on('keyup', function () {
    $("#div1").css('background', $(this).val());
});

Furthermore, using the same selector instead of this is impractical.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top