最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Simple Keypress Event Not working for textbox - Stack Overflow

programmeradmin3浏览0评论

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 ?

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 ?

Share Improve this question asked Nov 24, 2014 at 7:19 ABDABD 8892 gold badges13 silver badges29 bronze badges 6
  • try using event.keyCode == 13 – VSri58 Commented Nov 24, 2014 at 7:20
  • I tried just now that tooo.. But not working :( – ABD Commented Nov 24, 2014 at 7:22
  • keyCode with C in caps. See my answer. – VSri58 Commented Nov 24, 2014 at 7:25
  • are you adding the element in runtime or is it loaded with the page content – Manish Jangir Commented Nov 24, 2014 at 7:25
  • You code is working, have you included the jquery library to your page. here is working fiddle by your code jsfiddle/v3fggs1w – Vinay Pratap Singh Bhadauria Commented Nov 24, 2014 at 7:29
 |  Show 1 more ment

4 Answers 4

Reset to default 12

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
    }
});

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()
    }
 });

Try

event.KeyCode == 13

JS Code:

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

See this fiddle

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');
}
});
发布评论

评论列表(0)

  1. 暂无评论