I have several inputs, they are created dynamically
<input style="width:100%" class="fileDescription" type="text" name="' + descriptionId + '" id="' + descriptionId + '" placeholder="Write a file description, hit Enter to save" />
I would like to attach KeyPress event to all these Inputs and pass ID of the Input. How to do that? I have tried to use code below to attach event but that does not work. Also I do not know how to pass ID of the Input field to the binded event.
$('.fileDescription').bind('keypress', function(e) {
e.p开发者_如何转开发reventDefault();
alert("Works!");
});
Try this:
$('.fileDescription').live('keypress', function(e) {
e.preventDefault();
alert(this.id);
});
You'll see in the jsfiddle example how the 2nd element that was added dynamically also works.
JSFiddle Example
$('.fileDescription').bind('keydown', function(e) {
alert($(this).attr('id'));
});
Your code works perfectly for me...
http://jsfiddle.net/Jaybles/f6urc/
Use the live functionality, when dealing with dynamic content.
$(".fileDescription").live("keydown", function ()
{
// ...
});
精彩评论