Tomas
Tomas

Reputation: 18107

Bind several Inputs to OnKeyPress event

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.preventDefault();
            alert("Works!");

            });  

Upvotes: 1

Views: 2683

Answers (4)

Richard Dalton
Richard Dalton

Reputation: 35793

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

Upvotes: 4

cllpse
cllpse

Reputation: 21727

Use the live functionality, when dealing with dynamic content.

$(".fileDescription").live("keydown", function ()
{
   // ...
});

Upvotes: 0

Dutchie432
Dutchie432

Reputation: 29160

Your code works perfectly for me...

http://jsfiddle.net/Jaybles/f6urc/

Upvotes: 0

Chris Dixon
Chris Dixon

Reputation: 9167

$('.fileDescription').bind('keydown', function(e) {        
            alert($(this).attr('id'));
            });  

Upvotes: 2

Related Questions