Miroo
Miroo

Reputation: 805

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.

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

Upvotes: 0

Views: 984

Answers (2)

Shadow Wizzard
Shadow Wizzard

Reputation: 66398

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.

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1075587

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

Upvotes: 1

Related Questions