When editing text input, how can I perform a specific JavaScript action when I press the Enter key without the onSubmit handler form?

I have an HTML text box input.

How can I make a specific JavaScript call when I press the "Enter" button while editing this field? Pressing "Enter" currently reloads the entire page, presumably due to submitting the entire form.

NOTE. This HTML / JS code is simply included as a portlet to the large HTML page for the portal, which has one large main form wrapped around my code. Therefore, I can’t control the form - I can’t change the event or action onSubmit or wrap my field inputin a smaller form - otherwise the solution will be obvious :)

Also preferred is a solution that does not include adding a visible button to the form (I don't mind adding a button c display:hiddenif that’s what you need, but my attempt to do this did not seem to work).

It should be directly JS - no request / prototype / YUI.

PS is a search field, and the action will be a call to the existing search method on the page in JavaScript, if anyone is interested.

Thanks!

+3
4

, , -

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

... - :

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

javascript

<script type="text/javascript">
function noenter() {
    return !(window.event && window.event.keyCode == 13); 
}
</script>

,

onkeypress="return noenter()"

, , ...

+2

Enter? HTML-. , , , , , - onblur, , .

-1
source

Try adding the attribute "action = javascript: void (0)", as in the example below.

Enter causes the same action as pressing the submit button, but does not reload the page automatically.

<html>
<head></head>
<body>
    <div id="status"></div>
    <form action="javascript:void(0)">
        <input type="text" />
        <input type="submit" value="submit" onclick="document.getElementById('status').innerHTML = 'submitted';"/>
    </form>
    <script>document.getElementById('status').innerHTML = 'page loaded';</script>
</body>
</html>
-1
source

Source: https://habr.com/ru/post/1721224/


All Articles