It is hard to debug without html code. So please always remember that when you ask a question you should add enough code so that the problem was reproducable.
This code has a few things that should be changed
First of all avoid using $(selector)
more than it is necessary (it is memory consuming). If you want to perform a couple of operations like in your case on an element $("#medication_pill")
just save it to a variable.
Secondly on html form
elements it is better to use val()
function instead of text()
. Here is why
Lastly in an change
event you do not have to do make jQuery call to the select
element ($("#medication_id option:selected")
) since this event is bounded to this element. Instead you can just use $(this)
.
Here is an working example with desired functionality.
$("#medication_id").on('change', function() {
var textarea = $("#medication_pill");
textarea.val($("#medication_pill").val() + " + " + $(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="medication_id">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<textarea id="medication_pill"></textarea>
And here is an example with clearing select after change so that you can select tha same option couple of times in a row.
var select = $("#medication_id");
var textarea = $("#medication_pill");
select.on('change', function() {
textarea.val($("#medication_pill").val() + " + " + select.val());
select.val("");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="medication_id">
<option value=""></option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<textarea id="medication_pill"></textarea>