Andros Wong
Andros Wong

Reputation: 173

jQuery keypress is not working

I'm currently trying to add a textarea after a button is clicked. However, although the button click works, the textarea does not register any keypress events.

NOTE: There is a list of different files which why I attach a unique id to its id.

$(".add").click(function() {
    var id = $(this).attr("id");
    $("#" + id).after("<textarea placeholder = 'Add a description for this piece of work. Press enter to save it.' class = 'edit-work' id = 'edit-work" + id + "'></textarea>");
    $("textarea").not("#edit-work"+id).remove();                     
});

$(".edit-work").on('keypress', function(e) {
    alert('foo');
}); 

Upvotes: 1

Views: 292

Answers (2)

Amadan
Amadan

Reputation: 198324

$(".edit-work").on('keypress', ...) will only register the handler on currently existing .edit-work elements. If you add a new one, it will not have a handler attached. It's like telling all your employees not to produce any paper documentation, then hiring someone new without telling him anything, then wondering why he's doing the traditional office stuff with paper.

You want the live handler: $(editWorkAncestor).on('keypress', '.edit-work', ...), with editWorkAncestor being a document, or any node under which your .edit-work will appear (or a selector for one such). This will attach the handler to the ancestor, which will check each time if the event target matches the provided live selector.

Upvotes: 0

Marcos Casagrande
Marcos Casagrande

Reputation: 40404

when you bind the keypress listener to the textarea, the textarea doesn't exist. You need to bind the keypress to the document (or an existing parent)

$(document).on('keypress', ".edit-work", function(e){
    alert('foo');
});

More info on event delegation here:

Upvotes: 2

Related Questions