Keren Keren - 4 months ago 9
Javascript Question

Unable to get Dynamically added textarea value on keypress

It was working fine all these while, just now I re-factor codes for other functions, now this silly problem occurs and I've no idea why this happens.

Markup in jquery for textarea

+'<div class="ckit-container__ft" data-ckit-footer>'
+'<form action="" class="ckit-composer-form">'
+'<div class="ckit-composer">'
+'<textarea data-ckit-composer-textarea placeholder="Add your reply" autocomplete="off" name="message" class="form-control ckit-composer__textarea"></textarea>'
+'</div>'
+'</form>'
+'</div>


Binding keypress event

jQuery(function($){
jQuery('body').bind('keypress','[data-ckit-composer-textarea]',function(event)
{
console.log(jQuery('[data-ckit-composer-textarea]').val());//returns empty
console.log(jQuery(this).val());//returns empty string
});
});


Since the HTML markup exist outside
$(function(){..})
, I even tried cloning the template and find the relevant attribute to replace but no luck.

var fullChatView = '<div class="ckit-container__ft" data-ckit-footer>'
+'<form action="" class="ckit-composer-form">'
+'<div class="ckit-composer">'
+'<textarea data-ckit-composer-textarea placeholder="Add your reply" autocomplete="off" name="message" class="form-control ckit-composer__textarea"></textarea>'
+'</div>'
+'</form>'
+'</div>';

var test = $(fullchatView).clone();//ReferenceError: fullchatView is not defined
var val = test.find('[data-ckit-composer-textarea]').val();
console.log(val);

Answer
jQuery('body').on('keypress','[data-ckit-composer-textarea]',function(event) { });

Documentation

As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document. For earlier versions, the .bind() method is used for attaching an event handler directly to elements.

Comments