When editing a text input, how do I do a specific JavaScript action on hitting "Enter" key without the form's onSubmit handler?

forms, html, javascript

Solution

Assuming you have a text input something like

<input id="myTextBox" name="foo" value="bar">

... you could do something like this, after the document has loaded, and it will work in all mainstream browsers:

document.getElementById("myTextBox").onkeypress = function(evt) {
    evt = evt || window.event;
    var charCode = evt.keyCode || evt.which;
    if (charCode == 13) {
        // Suppress default action of the keypress
        if (evt.preventDefault) {
            evt.preventDefault();
        }
        evt.returnValue = false;

        // Do stuff here
    }
};

Problem

I have an HTML `input` text field. How can I perform a specific JavaScript call when hitting "Enter" button while editing that field? Currently, hitting "Enter" reloads the entire page, presumably due to submitting the entire form. NOTE: This HTML/JS code is merely included as a portlet into a large HTML page for a portal, which has one large master form wrapped all the way around my code. Therefore I can not control the form - can't change onSubmit event or action or wrap my `INPUT` field into a smaller form - otherwise the solution would be obvious :) Also, a solution that does not involve adding a visible button to the form is strongly preferable (I don't mind adding a button with `display:hidden` if that's what it takes, but my attempt to do so didn't seem to work). This needs to be straight up JS - no Query/Prototype/YUI is available. P.S. it's a search field and the action will be a call to an existing in-page JavaScript search method, if someone's curious. Thanks!

Original source