user2416047
user2416047

Reputation: 100

jQuery .text() will not update

My issue is that when there is a "keydown" event triggered, the textarea's text will not update with what is currently in the textarea, just what was originally in the textarea. Check out the Fiddle that helps me describe the issue. Click on the word test and try to edit the textarea that appears. Notice that the alerts still only result in "Test", not what it has been changed to.

<script>
$('#content').click(function () {
    var content = $('#content').text();
    $('#content').html("<textarea id='text'>" + content + "</textarea>");
    $('textarea').width($(window).width()).height($(window).height());
    $("#content").unbind('click');
});

$("body").delegate("textarea", "keydown",function(e){
    myAjaxFunction($('textarea').text());
    alert($('textarea').text());
});

function myAjaxFunction(value) {
$.post("update.php?filename=" + filename, { content: value });
}
</script>

Upvotes: 2

Views: 101

Answers (2)

Ron
Ron

Reputation: 6735

According to jquery text help, it said:

The .text() method cannot be used on form inputs or scripts. To set or get the text value of input or textarea elements, use the .val() method. To get the value of a script element, use the .html() method.

So just replace text() to be val(), check http://jsfiddle.net/qSbLp/4/

$('#content').click(function () {
    var content = $('#content').text();
    $('#content').html("<textarea id='text'>" + content + "</textarea>");
    $('textarea').width($(window).width()).height($(window).height());
    $("#content").unbind('click');
});

$("body").delegate("textarea", "keydown",function(e){
    alert($('textarea').val());
});

function myAjaxFunction(value) {
$.post("update.php?filename=" + filename, { content: value });
}

Upvotes: 0

Felix
Felix

Reputation: 38102

Some changes:

1) You need to use on() instead of delegate() because as of jQuery 1.7, .delegate() has been superseded by the .on() method

2) Use keyup instead of keydown event.

3) Use val() to get the value of your textarea

$("body").on("keyup", "textarea",function(e){
    alert($('textarea').val());
}); 

Updated Fiddle

Upvotes: 5

Related Questions