Edgar
Edgar

Reputation: 168

Add select form value into a textarea using jQuery

How can I add (and not replace) the value of a select input into a textarea.

For instance, I have:

HTML

<textarea id="text"></textarea>
<select id="test">
    <option value="foo">Foo</option>
    <option value="bar">Bar</option>
</select>

If I write "Stackoverflow" in the textarea, then I choose Foo in the select input, the textarea content should become "Stackoverflow foo".

I tried doing the following

Javascript

$("#text").val()

But it seems to replace the content of the textarea instead of adding values.

Upvotes: 2

Views: 3520

Answers (6)

vivek salve
vivek salve

Reputation: 991

$(document).ready(function(){
    $("#test").change(function(){
        var textAreaContent = $("#text").val();  //VALUE OF TEXTAREA
        var selectBoxVal = $(this).val();    //VALUE OF SELECT BOX
       $("#text").val(textAreaContent+" "+selectBoxVal);   //ADD THE VALUE INSIDE TEXTAREA
    });
});

Upvotes: 1

Jeff Noel
Jeff Noel

Reputation: 7618

Try the following, everytime the value of the select input changes, its selected option text is added to the textarea:

JavaScript/jQuery

$('#test').change(function(){
    $('#text').val($('#text').val()+" "+$('#test option:selected').text());
});

See this demo

Upvotes: 1

Adil Shaikh
Adil Shaikh

Reputation: 44740

$('#test').on('change',function(){
 var test = this;
 $('#text').val(function(_,v){
     return v + test.value;
 })
})

Upvotes: 2

palaѕн
palaѕн

Reputation: 73906

You can do this using .val( function(index, value) ):

$("#text").val(function (_, oldValue) {
    return oldValue + $('#test').val();
});

Upvotes: 1

Suresh Atta
Suresh Atta

Reputation: 121998

Simply in onChange function of select box write

$('#text').val($('#text').val()+'Foo'); 

Upvotes: 0

pandavenger
pandavenger

Reputation: 1027

Just get the current value and add to it

$("#text").val($("#text").val() + "Foo");

or EVEN BETTER use append()

$("#text").append("Foo");

Upvotes: 2

Related Questions