I have a form
with two text boxes, one select drop down and one radio button. When the enter key is pressed, I want
Using TypeScript, and avoid multiples calls on the function
let el1= <HTMLInputElement>document.getElementById('searchUser');
el1.onkeypress = SearchListEnter;
function SearchListEnter(event: KeyboardEvent) {
if (event.which !== 13) {
return;
}
// more stuff
}
If you're using jQuery:
$('input[type=text]').on('keydown', function(e) {
if (e.which == 13) {
e.preventDefault();
}
});
Override the onsubmit
action of the form to be a call to your function and add return false after it, ie:
<form onsubmit="javascript:myfunc();return false;" >
Some older browsers implemented keydown events in a non-standard way.
KeyBoardEvent.key is the way it is supposed to be implemented in modern browsers.
which and keyCode are deprecated nowadays, but it doesn't hurt to check for these events nonetheless so that the code works for users that still use older browsers like IE.
The isKeyPressed
function checks if the pressed key was enter and event.preventDefault()
hinders the form from submitting.
if (isKeyPressed(event, 'Enter', 13)) {
event.preventDefault();
console.log('enter was pressed and is prevented');
}
JS
function isKeyPressed(event, expectedKey, expectedCode) {
const code = event.which || event.keyCode;
if (expectedKey === event.key || code === expectedCode) {
return true;
}
return false;
}
document.getElementById('myInput').addEventListener('keydown', function(event) {
if (isKeyPressed(event, 'Enter', 13)) {
event.preventDefault();
console.log('enter was pressed and is prevented');
}
});
HTML
<form>
<input id="myInput">
</form>
https://jsfiddle.net/tobiobeck/z13dh5r2/
<div class="nav-search" id="nav-search">
<form class="form-search">
<span class="input-icon">
<input type="text" placeholder="Search ..." class="nav-search-input" id="search_value" autocomplete="off" />
<i class="ace-icon fa fa-search nav-search-icon"></i>
</span>
<input type="button" id="search" value="Search" class="btn btn-xs" style="border-radius: 5px;">
</form>
</div>
<script type="text/javascript">
$("#search_value").on('keydown', function(e) {
if (e.which == 13) {
$("#search").trigger('click');
return false;
}
});
$("#search").on('click',function(){
alert('You press enter');
});
</script>
Don't send the form on keypress "Enter":
<form id="form_cdb" onsubmit="return false">
Execute the function on keypress "Enter":
<input type="text" autocomplete="off" onkeypress="if(event.key === 'Enter') my_event()">