Tony
Tony

Reputation: 167

get textarea value from dynamic dom on keypress

I'am trying to get the value from a dynamic added dom elements, with inspiration from this answer:

Jquery .keypress on a dynamically added input

My code:

var commentbox = $('<div class=\"span6\"><textarea rows=\"1\" data-replyparent=\"'+replyparentid+'\" class="replytocomment" id=\"'+commentboxid+'\" style=\"display:none;\"></textarea></div>')
    .keypress (function (e) {
        var keyCode = e.keyCode || e.which;
        if (keyCode == 13) {
            console.log("it seems to work: "+ $(this).val());


            $.ajax({
                url: '/add/comment',
                type: 'POST',
                data: {
                    id: id,
                    parent: replyparentid,
                    comment: comment
                },
                success: function(){
                }
            });
        }
    })
    .insertAfter(placeholder)
;
//then insert the emojionearea after the placeholder
//$(commentbox).insertAfter(placeholder);
$('.replytocomment').emojioneArea({
    pickerPosition: "bottom",
    filtersPosition: "bottom",
    tonesStyle: "bullet"
});

I can't figure out how to get the value from the textarea on keycode 13, how is that possible, when using it "inline".

In the console I only get "it seems to work" but not the value form the textarea.

If I update the var commentbox, to have something in the textarea, like this:

var commentbox = $('<div class=\"span6\"><textarea rows=\"1\" data-replyparent=\"'+replyparentid+'\" class="replytocomment" id=\"'+commentboxid+'\" style=\"display:none;\">TESTING</textarea></div>')

It works with: $(this).find('textarea').val()

So I guess it might have something to do with the listener? Seems a bit strange though, because when I log the entire element like this: console.log($(this).find('textarea')); To the console, it shows the correct an updated value in the valuefield.

Best regards.

Upvotes: 0

Views: 375

Answers (1)

Programmer
Programmer

Reputation: 2123

The event is set on the wrapping div, not the textarea, so this inside the eventhandler is the div. Use $(this).find('textarea').val() to get the value from the textarea.

Upvotes: 2

Related Questions