Reputation: 168
How can I add (and not replace) the value of a select
input into a textarea
.
For instance, I have:
<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
$("#text").val()
But it seems to replace the content of the textarea instead of adding values.
Upvotes: 2
Views: 3520
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
Reputation: 7618
Try the following, everytime the value of the select
input changes, its selected option text is added to the textarea
:
$('#test').change(function(){
$('#text').val($('#text').val()+" "+$('#test option:selected').text());
});
Upvotes: 1
Reputation: 44740
$('#test').on('change',function(){
var test = this;
$('#text').val(function(_,v){
return v + test.value;
})
})
Upvotes: 2
Reputation: 73906
You can do this using .val( function(index, value) ):
$("#text").val(function (_, oldValue) {
return oldValue + $('#test').val();
});
Upvotes: 1
Reputation: 121998
Simply in onChange
function of select box
write
$('#text').val($('#text').val()+'Foo');
Upvotes: 0
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