Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery SELECT with Textarea

Just wondering if someone can help me on a problem, I don't fully undersand why it doesn't work.

I have this fiddle, http://jsfiddle.net/uomt99zp/

What it is doing: When you select from the drop down box, insert that word into the textarea. Which it DOES, when the textarea isn't "touched".

If you type something into the box, and then try to select an item, it doesn't work.

I'm not sure why this doesn't update the textarea. Perhaps someone can shed some light on this issue?

<textarea name="template" required="required" class="template form-control" rows="6"></textarea>
<select class="templatesAvailableFields">
<option>Select One</option>
    <option>Test1</option>                     
    <option>Test2</option>
    <option>Test3</option>
</select>

$('.templatesAvailableFields').on('change', function() {
        var text = $('.templatesAvailableFields option:selected').text();
        $('.template').append(text);
});
like image 685
Justin Avatar asked Mar 25 '15 05:03

Justin


3 Answers

You need to set value using .val():

$('.template').val($('.template').val()+text);

Working Demo 1

Also .val() can have callback function which can be used for setting a new value:

function Type: Function( Integer index, String value ) => String A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old value as arguments.

$('.template').val(function(i,v){ return v+ text});

Working Demo 2

like image 77
Milind Anantwar Avatar answered Nov 13 '22 21:11

Milind Anantwar


You can try val(function) with old value + new text to append,

$('.templatesAvailableFields').on('change', function() {
    var text = $('.templatesAvailableFields option:selected').text();
    $('.template').val(function(ind,val){
         return val+text;
    });
});

Live Demo

like image 1
Rohan Kumar Avatar answered Nov 13 '22 20:11

Rohan Kumar


To answer to the "why" it does not work, it's because, the contents of a textarea represent its default value. So, when you append an element to the textarea, you change the default value of this textarea.

So it changes the textarea as long as you did not type in. Once you typed in, the default value is no more used, even if you remove all the text of the textarea.

like image 1
Pierre Avatar answered Nov 13 '22 20:11

Pierre