Skip to content Skip to sidebar Skip to footer

How To Stop A Button From Being Fired When Press Enter

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.

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

Solution 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.


Post a Comment for "How To Stop A Button From Being Fired When Press Enter"