how to stop a button from being fired when press enter

我只是一个虾纸丫 提交于 2019-12-25 04:43:26

问题


I am using this function to handle enter click on a search textbox but it fires another button in the page, how to stop that button from being fired and call my search() function.

InputKeyPress(e) {
    if (window.event) {
        if (event.keyCode == 13) {
            search();
        }
    } else {
        if (e) {
           if (e.which == 13) {
               search();
           }
        }
    }
 }

回答1:


In the keyCode == 13 case, you need to prevent the default action of the keypress event. The standard way to do this is to call the preventDefault function on the event object (if it has one; it doesn't on earlier versions of IE). The older way is to return false from your event handler function. There's no real harm in a "belt and braces" approach of doing both. :-)

You can also shorten your function a bit:

function InputKeyPress(e) {
    var keyCode;

    e = e || window.event;
    keyCode = e.keyCode || e.which;
    if (keyCode == 13) {
        search();
        if (e.preventDefault) {
            e.preventDefault();
        }
        return false;
    }
}



回答2:


You need to add "return false" like this:

function InputKeyPress(e) {
    if (!e)
        e = window.event;
    var keyCode = e.keyCode || e.which;
    if (keyCode == 13) {
        search();
        return false;
    }

    return true;
}

And also change the call from the textbox to this:

<input .... onkeypress="return InputKeyPress(event);" ...>

Meaning not just call the function but "return" it.



来源:https://stackoverflow.com/questions/4237032/how-to-stop-a-button-from-being-fired-when-press-enter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!