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

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!