Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop page refreshing when 'enter' is pressed in input text element

Tags:

javascript

Is there a way to stop a webpage from refreshing completely when the enter button is pressed in a input text element?

I'm looking to create a search field that I can get the text from when enter is pressed to filter objects and only display the ones that contain text from the search field.

I've tried the following to try and catch the enter button but it does not work.

function setupSearchField() {
    document.getElementById("searchField").onKeyDown = function(event) {
        var holder;
        if (window.event) {
            holder = window.event.keyCode;
        } else {
            holder = event.which;
        }
        keyPressed(holder);
    }
}

function keyPressed(key) {
    if (key == 13) {
        event.cancelBubble = true;
        return false;
    }
}
like image 988
Peter Bushnell Avatar asked May 15 '12 11:05

Peter Bushnell


People also ask

How do you stop a page from refreshing?

Click the Start button, type “internet options” and select Internet Options in the search results. In the Internet Properties window, click “Custom tab -> Custom level,” then in the Security Settings window, scroll down until you find “Allow META REFRESH.” Disable this option and click OK.

How do you disable the Enter key of an input textbox?

Disabling enter key for the form addEventListener('keypress', function (e) { if (e. keyCode === 13 || e. which === 13) { e. preventDefault(); return false; } });

How do I stop page reload/refresh on hit back button?

You have to detect browser back button event and pass as an input of the page you want do prevent URL reload that indicates you if you came from a back button click. this code: $(window). on('popstate', function(event) { alert("pop"); });


2 Answers

If the input element is inside a form, and that form is not actually being submitted to the server, remove the form.

The reason your code doesn't work is becaue the onkeydown event should be in lowercase, and you aren't actually returning something in it (try return keyPressed(holder); - or just move the keyPressed function's code into setupSearchField, since it seems kind of pointless to me to have it as a separate function).

like image 96
Niet the Dark Absol Avatar answered Oct 05 '22 14:10

Niet the Dark Absol


This happens when there is only one text input, regardless of whether your button (if any) has type="submit" or not. It's documented here. http://www.w3.org/MarkUp/html-spec/html-spec_8.html#SEC8.2 So, as suggested by other people earlier, you then have to simply stop this default behavior.

like image 22
Rahul Dole Avatar answered Oct 05 '22 12:10

Rahul Dole