Reputation: 8827
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
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
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:
.text
to .val
which will always change a form field value correctlyfind
and replaced with method for searching inside this
: $('option:selected', this)
Here's a jsFiddle for you: http://jsfiddle.net/sp5L4/2/
Upvotes: 2
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
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