ThinkingInBits
ThinkingInBits

Reputation: 11482

jQuery keypress event not firing

I have a form that when the user hits edit, it changes the field from text to a textbox with a class of cat_name_edit.

The following code does not trigger when pressing any key in the textbox. Could it have something to do with the fact that I've already changed the text into a textbox?

  $(".cat_name_edit").keypress(function() {

     alert("hi"); 

  });

I've also tried .click() and .keydown() with no luck. Any ideas?

Upvotes: 0

Views: 2632

Answers (4)

Pawan
Pawan

Reputation: 605

or you could also use EventDelegation. Attach your click event to the parent which contains these textboxes, and in the function check if the target that was clicked has the class cat_name_edit and then perform your operation.

Upvotes: 0

Purag
Purag

Reputation: 17071

I put this into a fiddle keypress() works fine:

$(".cat_name_edit").keypress(function(e) {
    $(this).replaceWith("<textarea class=\"cat_name_edit\"></textarea>");
    $("textarea.cat_name_edit").focus();
});

keyup() would have worked too.

I've also gone to the liberty of making the function that replaces the input with a textarea.

Upvotes: 0

ShankarSangoli
ShankarSangoli

Reputation: 69915

I think the elements are not present on page load so the events are not attached. Try using jQuery live.

$(".cat_name_edit").live('keypress', (function() {

     alert("hi"); 

  });

Upvotes: 0

ThinkingInBits
ThinkingInBits

Reputation: 11482

Ok, apparently I had to use .live()

Upvotes: 1

Related Questions