简体   繁体   English

简单的按键事件不适用于文本框

[英]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. 我有一个文本框,其中为Enter键编写了按键功能,该按键应显示警报。

Here is my html and script. 这是我的HTML和脚本。

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. 但是当我在文本框中按Enter时,我没有收到警报。

What is the mistake i am doing and how can i fix this ? 我正在做的错误是什么,我该如何解决?

I think you are adding this element dynamically in the HTML and .keypress will only work on pre loaded elements. 我认为您是在HTML中动态添加此元素,.keypress仅适用于预加载的元素。 jQuery has provided $(document).on for dynamically added elements. jQuery为动态添加的元素提供了$(document).on。

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

Hey you should try keypress event like this 嘿,你应该尝试这样的keypress事件

$("#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: JS代码:

$( "#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. 将此放置在document.ready块中,以便在加载整个dom后触发。 Eventually mark your script with defer attribute. 最终用defer属性标记您的脚本。

You should use both which and keyCode , bacause they don't work on all browsers. 您应该同时使用which和keyCode,因为它们不能在所有浏览器上都起作用。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM