ABD
ABD

Reputation: 889

Simple Keypress Event Not working for textbox

I have a textbox in which i written keypress function for the Enter Key, which should show alert.

Here is my html and script.

Here is my Textbox :

<li>
<input type="text" class="fi_top" placeholder="Howdy" id="howdy" value="">
</li>

And inside the page i have

Script :

$( "#howdy" ).keypress(function( event ) 
{
  if ( event.which == 13 ) {
  alert('okay');
}
});

But i am not getting alert while i press enter at the textbox.

What is the mistake i am doing and how can i fix this ?

Upvotes: 1

Views: 12815

Answers (4)

Manish Jangir
Manish Jangir

Reputation: 5437

I think you are adding this element dynamically in the HTML and .keypress will only work on pre loaded elements. jQuery has provided $(document).on for dynamically added elements.

$(document).on("keypress", "#howdy", function (e) {
    if (e.keyCode == 13 || e.which == '13') {
       //Do your work
    }
});

Upvotes: 12

Beri
Beri

Reputation: 11610

Place this in document.ready block, so that it will trigger after whole dom will load. Eventually mark your script with defer attribute.

You should use both which and keyCode , bacause they don't work on all browsers.

$( "#howdy" ).keypress(function( event ) 
{
  if ( event.which == 13 || event.keyCode == 13) {
  alert('okay');
}
});

Upvotes: 1

VSri58
VSri58

Reputation: 3761

Try

event.KeyCode == 13

JS Code:

$( "#howdy" ).keypress(function( event ) 
{
  if ( event.keyCode == 13 ) {
  alert('okay');
}
});

See this fiddle

Upvotes: 1

Neeraj
Neeraj

Reputation: 4489

Hey you should try keypress event like this

$("#howdy").keypress(function() {
  var keycode = (event.keyCode ? event.keyCode : event.which);
    if (keycode == '13') {
        callAjaxGetJoiningDate($(this).val());
        event.preventDefault()
    }
 });

Upvotes: 1

Related Questions