开发者

Input field type text has property onkeypress call function more then one time

开发者 https://www.devze.com 2023-03-20 02:39 出处:网络
<input type=text id=Keywordtextbox onkeypress=fb()maxlength=&quo开发者_如何学编程t;30" style=width:100px >
<input type=text id=Keywordtextbox onkeypress=fb()  maxlength=&quo开发者_如何学编程t;30" style=width:100px >

The function fb() is:

function fb() {    
        $("#Keywordtextbox").keypress(function (event) {
            if (event.keyCode == 13) {
                alert('123');
              //  document.getElementById('AddButton').click();
            }
        });           
} 

My problem is when is the click enter event is not fired. When I click a second time it shows me an alert box; when I click on third time it shows me the alert three times. How can I handle that event so on enter key press only once time this fb() function is called.


You should not call fb in onKeyPress AND register the .keypress jQuery event. Do one or the other, not both! You have double registered for key events and then after the first key, you get triple registered.

When you get a key event, it calls both fb() and it calls your inner function handler for .keyPress. When fb() gets called again, you end up registering again for the keypress event and that happens each time a new key is pressed.

I'd recommend you get rid of the onkeypress=fb() from the HTML.

Then, just call fb() once in your startup code to register the keypress event handler. After that, you should just get one key event per press.

Here's a working example: http://jsfiddle.net/jfriend00/Zyftj/

HTML:

<input type="text" id="Keywordtextbox"  maxlength="30" style="width:100px"> 

JS (called in page ready handler):

$("#Keywordtextbox").keypress(function (event) {
    if (event.keyCode == 13) {
        console.log("123");
    }
});           
0

精彩评论

暂无评论...
验证码 换一张
取 消