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;
}
}
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.
Disabling enter key for the form addEventListener('keypress', function (e) { if (e. keyCode === 13 || e. which === 13) { e. preventDefault(); return false; } });
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"); });
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With