March 11, 2012
Setting Jquery Enter Key Event For Dynamically Generated TextBox
Question by irfanmcsd
How to set jquery keyup event for dynamically generated textbox instead of static text box as shown below?
$('#statictextboxid').keyup(function(e) {
//alert(e.keyCode);
if(e.keyCode == 13) {
alert('Enter key was pressed.');
}
});
Answer by Starx
Bind the event using .on() to keep it attached for dynamically generated elements also
//Simulate dynamically generated textbox
$("body").append("<input type='text' class='textbox' />");
// Now bind the event
$('.textbox').on('keyup', function(e) {
//alert(e.keyCode);
if(e.keyCode == 13) {
alert('Enter key was pressed.');
}
});
Demo with the simulated version