jquery val function get new value from textarea
-
06-07-2021 - |
Question
here is a jsfiddle
here is my html
<table id="commentsTable">
<tr>
<td name="userid"> JIM </td>
<td name="comment" id="68" class="commentTD"> something </td>
<td><a class="edit" href="#">edit</a></td>
</tr>
</table>
and my js:
var update = "update";
$("a.edit").click(function(e) {
e.preventDefault();
var comment = $(this).closest("tr").find('.commentTD');
comment.html('<textarea name="comment" class="commentArea">' + comment.text() + '</textarea>');
$(this).removeClass().addClass(update).text(update);
bindUpdate();
});
function bindUpdate() {
$("a." + update).click(function(e) {
e.preventDefault();
var commentNewText = $(this).closest('tr').find('textarea.commentArea').val();
alert(commentNewText);
});
};
I am able to add a textarea and bind a click event to it, but I can't seem to get the new value, I get the old one...
Solution
The problem is that you're not unbinding the old event from your link, so it still adds a new textarea each time you click it and only THEN it calls the bindUpdate() functionality.
See this updated jsFiddle: http://jsfiddle.net/RALDF/8/
EDIT: I would suggest to save value of $(this)
into a variable and re-use it, since you're calling it multiple times, which has a negative impact on performance /jQuery needs to make new object every time you do $(this)/
OTHER TIPS
You're getting your first handler triggered before the new one. If you add unbind
to the first handler it work ok (fiddle). To acheive this in a more predictable way you may extract your handlers to the separate functions.