sidy3d
sidy3d

Reputation: 549

Jquery keyup event not working when using classes

I have an input field with a class of replyComment and I have a event handler that will determine if the enter key was pressed.

<input class="replyComment" placeholder="Enter Reply" type="text">
$('#replyComment').keyup(function (e) {
   alert(e.keyCode);
   if (e.keyCode == 13) {
      alert('Enter key was pressed.');
   }
});

The problem is that the event will not fire. Regards,

Upvotes: 0

Views: 4875

Answers (3)

Vatsal
Vatsal

Reputation: 2128

As everyone has mentioned "#" refers to the elements denoted by id's. Since the code you are using ->

<input class="replyComment" placeholder="Enter Reply" type="text">

is referring to class you need to access it via . selector. So ideally your code should be like

    $(".replyComment").keyup(function(){});

There may be cases when this also does not work if the element that has this class is not present in the DOM at the time of page load. If this is being introduced in your page after your page is loaded by some JS event or anything then you will have to bind it with the DOM using the "on" selector.

SO your code should be like

jQuery(document ).on( "keyup", ".replyComment", function(){ });

Hope this will be of any help

Happy Learning :)

Upvotes: 5

Sachin Kalia
Sachin Kalia

Reputation: 1107

Kindly use (".") instead of ("#") in your code like given below:

$('.replyComment').keyup(function (e) {
   alert(e.keyCode);
   if (e.keyCode == 13) {
      alert('Enter key was pressed.');
   }
});

Whenever you want to trigger an element than use "." instead of "#". ("#") always work with an id element.

Hope it will sort out your proble

Upvotes: 0

Grant Thomas
Grant Thomas

Reputation: 45058

# specifies an id selector, use a leading period (.) to specify a class selector:

$('.replyComment').keyup( ... )

Upvotes: 2

Related Questions