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?
You need to use
.val()instead of.text():Demo: http://jsfiddle.net/jtbowden/HaZWC/
.text()essentially sets the text between the tags<textarea></textarea>, which sets the default value of thetextarea. 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.