Reputation: 938
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;
}
}
Upvotes: 6
Views: 8767
Reputation: 1
Just add the following javascript code to your Visualforce page:
<script type='text/javascript'>
function stopRKey(evt)
{
var evt=(evt) ? evt : ((event) ? event : null);
var node=(evt.target)?evt.target:((evt.srcElement)?evt.srcElement:null);
if ((evt.keyCode == 13) && (node.type=="text")) {return false;}
}
document.onkeypress = stopRKey;
</script>
Upvotes: 0
Reputation: 3093
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.
Upvotes: 2
Reputation: 261
Is your search field inside a element ? Then hitting 'enter' fires a submit event to the form element.
In this case you could process your filtering by defining onsubmit on the form element.
<form id="searchForm">
<input type="text" name="search" />
</form>
<script>
document.getElementById('searchForm').onsubmit = function() {
var searchValue = this.search.value;
// process
return false;
}
</script>
Something like this maybe.
Upvotes: 0
Reputation: 324840
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).
Upvotes: 6