pingu
pingu

Reputation: 8827

Change the text of a textarea, from the selected item in a select

I have this function that successfully populates a textarea with text from a select, when the select is changed.

function Favourites()
{
  $('select#favourites').change(function() {
    var text = $(this).find('option:selected').attr('data-post');
    $('textarea#post').text(text);
  });
}

Problem is if I change the select, delete the contents of the textarea, and change the select again, it no longer populates the textarea.

Any idea why please?

Upvotes: 1

Views: 300

Answers (4)

Ohgodwhy
Ohgodwhy

Reputation: 50798

Use the 'on' method to attach/listen to event handlers throughout the DOM.

$('select#favourites').on('change', function(){
  var text = $(this).find('option:selected').attr('data-post');
  $('textarea#post').text(text);
});

Upvotes: 0

Steve O
Steve O

Reputation: 5794

Is there a reason that the change function is inside the Favourites function? You simply need it in your DOM ready function like this:

$(document).ready(function(){

    $('select#favourites').change(function() {
        var text = $('option:selected', this).attr('data-post');
        $('textarea#post').val(text);
    });

});

I've also changed:

  • the .text to .val which will always change a form field value correctly
  • removed find and replaced with method for searching inside this: $('option:selected', this)

Here's a jsFiddle for you: http://jsfiddle.net/sp5L4/2/

Upvotes: 2

Jeff B
Jeff B

Reputation: 30099

You need to use .val() instead of .text():

 $('#post').val(text);

Demo: http://jsfiddle.net/jtbowden/HaZWC/

.text() essentially sets the text between the tags <textarea></textarea>, which sets the default value of the textarea. This is fine as long as the user has not typed anything in the text box. But, just like when you do <textarea>My Text</textarea> in html, the default value is always overridden by what the user inputs. Because this is an input, the .val() function sets the actual value of the input, which overrides the default value.

Upvotes: 2

Ascherer
Ascherer

Reputation: 8093

Try using something like on() (the new live()), also, use val() and not text(). might be able to use data() too

$(document).on('change', 'select#favourites', function() {
    var text  = $(this).find('option:selected').data('post');
    $('textarea#post').val(text);
});

Upvotes: 1

Related Questions