http://codepen.io/abdulahhamzic/pen/YqMQwB
How do I make it so that when I press enter on a text input, it calls a function? I tried using this:
<input type="text" onkeypress="clickPress()">
But the problem is I only want to press enter to call that function, not press any key. How do I achieve that?
2022 Update: onkeypress is deprecated.
You can use onKeyDown instead
What you'd want to do is check whether the event's key is the enter key:
In your html, add the event argument
<input type="text" onkeypress="clickPress(event)">
And in your handler, add an event parameter
function clickPress(event) {
if (event.keyCode == 13) {
// do something
}
}
2022 Update: event.keyCode is deprecated on many browsers.
You should do this now:
function clickPress(event) {
if (event.key == "Enter") {
// do something
}
}
Use a form instead (the submit event only runs once instead of every key press):
// Attach the event handler to the form element
document.querySelector('.js-form')?.addEventListener('submit', e => {
e.preventDefault();
alert(e.currentTarget.myText.value);
});
<form class="js-form">
<input type="text" name="myText">
</form>
The Enter button has a keyCode of 13, so you can use the keypress event using jQuery
$("input").keypress(function(event) {
if (event.which == 13) {
alert("Enter was pressed");
}
});
or, in pure javascript:
<input type="text" onkeypress="clickPress(event)">
function clickPress(event) {
if (event.keyCode == 13) {
// do something
}
}
Get the event's keycode and test if it's enter (keycode 13)
<script>
function clickPress(e){
if (event.keyCode == 13) {
// Enter was pressed
alert("enter");
}
}
</script>
<input type="text" onkeypress="clickPress(event)" />
jsfiddle
There could be several "better" ways to do what you want to do but just for the sake of simplicity, you could do this:
<input type="text" id="txt">
Instead of listening to the onkeypress you could attach an event listener within the <script></script> tags and do this:
var myText = document.getElementById("txt");
myText.addEventListener("keyup", function(e) {
if (e.which === 13) {
//The keycode for enter key is 13
alert(e.target.value);
}
});
And yeah this is definitely a duplicate question.
In my page there are two buttons. For enter key functionality I have written the following jQuery code.
$(function () {
$("#first-button-id").keyup(function (e) {
if (e.keyCode == '13') {
e.preventDefault();
}
}).focus();
$("#second-button-id").keyup(function (e) {
if (e.keyCode == '13') {
e.preventDefault();
}
}).focus();
});
But always when click on enter key first one is firing. Please tell me how to handle the multiple button enter key functionality.
Try something like this
HTML :
<label>TextBox : </label>
<input id="textbox" type="text" size="50" />
<label>TextBox 2: </label>
<input id="textbox2" type="text" size="50" />
JQuery
$('#textbox , #textbox2').keyup(function(event){
var keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode == '13'){
alert('You pressed a "enter" key in textbox');
}
event.preventDefault();
}).focus();
DEMO
Some browser prefer keycode and other use which ... I suggest you to use both..
You do not need to focus on two buttons at the same time. Try doing something like this:
$("#button1").keypress(function(event){
if ( event.which == 13 ){
//Do something}
$("#button2").keypress(function(event){
if( event.which == 13 ){
//Do something else}
The problem i think is with your event.preventDefault() function which stops the propogation of the event once a function is executed. In your case, your first function might be getting completed before the second one and hence the second one gets aborted in the middle.
$("#first-button-id , #second-button-id ").keyup(function(event){
if ( event.which == 13 ) {
alert("you pressed enter.");
event.preventDefault();
}
}
The reason the first submit button is always firing is because that's the default behavior of a web page which you haven't actually altered with your code.
Try this:
$(function () {
$("#first-button-id, #second-button-id").keyup(function (e) {
e.preventDefault();
e.stopImmediatePropagation();
if (e.keyCode == '13') {
$(this).trigger("click");
}
});
});
What you seem to be asking about strikes me as rather odd. It looks like you want second-button to be 'clicked' if the focus is on second-button and enter is pressed. Tabbing until the focus is on the correct button is really the only practical way this could happen.
Try this.
$('#first-button-id').on("keydown", function (e)
{
if (e.keyCode == 13)
{
e.preventDefault();
$("first-button-id").click();
}
});
I have a web application where on one specific screen I have to make sure the user clicked the button using the mouse as opposed to just pressing enter or space.
I have written this code:
$('button').keydown(function (e) {
if (e.which === 10 || e.which === 13 || e.which === 32) {
return false;
}
});
However, this only works for enter. The form can still be submitted by pressing space on a button. I am just wondering what caused this inconsistency and how to get around it?
Edit:
Example fiddle: http://jsfiddle.net/billccn/3JmtY/1/. Check the second check box and pressing enter while the focus is on the button will have no effect. If I further disable the input and expand the keydown trapping to the whole form, then enter cannot be used to submit the form.
Edit 2:
I do have a backup plan which is replacing the button with a link or even a plain div and use the click event to submit the form programmatically. However, extra work is required to make it look like a button so I'd rather use a button is possible.
Just found out: handling space (32) on keyup will prevent the click event.
Updated fiddle: http://jsfiddle.net/3JmtY/2/
Missed the Point of your Question. After some googleing if found the following trick:
Bind the keypress event to your from and listen to it's keycode. If the keycode is 13
(enter), prevent all default actions (event.preventDefaul()) and prevent further event bubbeling ( return false; ).
Her is a fiddler code example:
HTML:
<form id="target" action="destination.html">
<input type="text" value="Hello there" />
<input type="submit" value="Go" />
</form>
<div id="other">Trigger the handler</div>
JavaScript:
$('#target').keypress(function (event) {
var code = event.keyCode || event.which;
if (code == 13) {
event.preventDefault();
return false;
}
});
$('#target').submit(function (event, data2) {
debugger;
alert('test');
return false;
});
Fiddler: http://jsfiddle.net/ggTDs/
Note that the form is not submited when enter is clicked!
Use below code. 13 for Enter key and 32 for Spacebar.
$("#form_id").on('keydown keyup keypress', function( e ) {
if ( e.keyCode == 13 || e.which == 13 || e.which == 32 ) {
e.preventDefault();
return false;
}
});
<form name='qform'>
<textarea name='q' rows='3' cols='60' wrap='hard' id='q' onkeydown="if (event.keyCode == 13) document.getElementById('clickit').click()"></textarea>
<input type='button' value='search' id='clickit' onclick="get();">
</form>
I have this form... it doesn't have a submit button because I am using jquery and under this form is a div area where the results will be shown. It is a search engine that does not have an input box but instead has a textarea. This is because it will be a multiple word searcher.
The problem is that if I press enter, the query is submitted and everything is ok ... but the focus on textarea goes down one line and that is a problem for me.
Basically I want the enter to have that one function only(submit) end nothing else.
$(document).ready(function() {
$('textarea').keypress(function(event) {
if (event.keyCode == 13) {
event.preventDefault();
}
});
});
Why not just use <input type="text"> if you don't want multiple lines? You mentioned it will be a "multiple word searcher". Why does this require a <textarea>?
Update
Try this
$('textarea').bind('keypress', function(e) {
if ((e.keyCode || e.which) == 13) {
$(this).parents('form').submit();
return false;
}
});
In the jquery function, use event.preventdefault and next do what you like.
For example
<script>
$("a").click(function(event) {
event.preventDefault();
//Do your logic here
});
</script>
http://api.jquery.com/event.preventDefault/
Pure javascript:
document.addEventListener('keypress', function (e) {
if (e.keyCode === 13 || e.which === 13) {
e.preventDefault();
return false;
}
})
I have a form with two text boxes, one select drop down and one radio button. When the enter key is pressed, I want to call my JavaScript function, but when I press it, the form is submitted.
How do I prevent the form from being submitted when the enter key is pressed?
if(characterCode == 13) {
// returning false will prevent the event from bubbling up.
return false;
} else{
return true;
}
Ok, so imagine you have the following textbox in a form:
<input id="scriptBox" type="text" onkeypress="return runScript(event)" />
In order to run some "user defined" script from this text box when the enter key is pressed, and not have it submit the form, here is some sample code. Please note that this function doesn't do any error checking and most likely will only work in IE. To do this right you need a more robust solution, but you will get the general idea.
function runScript(e) {
//See notes about 'which' and 'key'
if (e.keyCode == 13) {
var tb = document.getElementById("scriptBox");
eval(tb.value);
return false;
}
}
returning the value of the function will alert the event handler not to bubble the event any further, and will prevent the keypress event from being handled further.
NOTE:
It's been pointed out that keyCode is now deprecated. The next best alternative which has also been deprecated.
Unfortunately the favored standard key, which is widely supported by modern browsers, has some dodgy behavior in IE and Edge. Anything older than IE11 would still need a polyfill.
Furthermore, while the deprecated warning is quite ominous about keyCode and which, removing those would represent a massive breaking change to untold numbers of legacy websites. For that reason, it is unlikely they are going anywhere anytime soon.
Use both event.which and event.keyCode:
function (event) {
if (event.which == 13 || event.keyCode == 13) {
//code to execute here
return false;
}
return true;
};
event.key === "Enter"
More recent and much cleaner: use event.key. No more arbitrary number codes!
NOTE: The old properties (.keyCode and .which) are Deprecated.
const node = document.getElementsByClassName("mySelect")[0];
node.addEventListener("keydown", function(event) {
if (event.key === "Enter") {
event.preventDefault();
// Do more work
}
});
Modern style, with lambda and destructuring
node.addEventListener("keydown", ({key}) => {
if (key === "Enter") // Handle press
})
Mozilla Docs
Supported Browsers
If you're using jQuery:
$('input[type=text]').on('keydown', function(e) {
if (e.which == 13) {
e.preventDefault();
}
});
Detect Enter key pressed on whole document:
$(document).keypress(function (e) {
if (e.which == 13) {
alert('enter key is pressed');
}
});
http://jsfiddle.net/umerqureshi/dcjsa08n/3/
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;" >
A react js solution
handleChange: function(e) {
if (e.key == 'Enter') {
console.log('test');
}
<div>
<Input type="text"
ref = "input"
placeholder="hiya"
onKeyPress={this.handleChange}
/>
</div>
So maybe the best solution to cover as many browsers as possible and be future proof would be
if (event.which === 13 || event.keyCode === 13 || event.key === "Enter")
Here is how you can do it using JavaScript:
//in your **popup.js** file just use this function
var input = document.getElementById("textSearch");
input.addEventListener("keyup", function(event) {
event.preventDefault();
if (event.keyCode === 13) {
alert("yes it works,I'm happy ");
}
});
<!--Let's say this is your html file-->
<!DOCTYPE html>
<html>
<body style="width: 500px">
<input placeholder="Enter the text and press enter" type="text" id="textSearch"/>
<script type="text/javascript" src="public/js/popup.js"></script>
</body>
</html>
Below code will add listener for ENTER key on entire page.
This can be very useful in screens with single Action button eg Login, Register, Submit etc.
<head>
<!--Import jQuery IMPORTANT -->
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<!--Listen to Enter key event-->
<script type="text/javascript">
$(document).keypress(function (e) {
if (e.which == 13 || event.keyCode == 13) {
alert('enter key is pressed');
}
});
</script>
</head>
Tested on all browsers.
A jQuery solution.
I came here looking for a way to delay the form submission until after the blur event on the text input had been fired.
$(selector).keyup(function(e){
/*
* Delay the enter key form submit till after the hidden
* input is updated.
*/
// No need to do anything if it's not the enter key
// Also only e.which is needed as this is the jQuery event object.
if (e.which !== 13) {
return;
}
// Prevent form submit
e.preventDefault();
// Trigger the blur event.
this.blur();
// Submit the form.
$(e.target).closest('form').submit();
});
Would be nice to get a more general version that fired all the delayed events rather than just the form submit.
A much simpler and effective way from my perspective should be :
function onPress_ENTER()
{
var keyPressed = event.keyCode || event.which;
//if ENTER is pressed
if(keyPressed==13)
{
alert('enter pressed');
keyPressed=null;
}
else
{
return false;
}
}
A little simple
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()">
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
}
<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>
native js (fetch api)
document.onload = (() => {
alert('ok');
let keyListener = document.querySelector('#searchUser');
//
keyListener.addEventListener('keypress', (e) => {
if(e.keyCode === 13){
let username = e.target.value;
console.log(`username = ${username}`);
fetch(`https://api.github.com/users/${username}`,{
data: {
client_id: 'xxx',
client_secret: 'xxx'
}
})
.then((user)=>{
console.log(`user = ${user}`);
});
fetch(`https://api.github.com/users/${username}/repos`,{
data: {
client_id: 'xxx',
client_secret: 'xxx'
}
})
.then((repos)=>{
console.log(`repos = ${repos}`);
for (let i = 0; i < repos.length; i++) {
console.log(`repos ${i} = ${repos[i]}`);
}
});
}else{
console.log(`e.keyCode = ${e.keyCode}`);
}
});
})();
<input _ngcontent-inf-0="" class="form-control" id="searchUser" placeholder="Github username..." type="text">
<form id="form1" runat="server" onkeypress="return event.keyCode != 13;">
Add this Code In Your HTML Page...it will disable ...Enter Button..
Cross Browser Solution
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');
}
Minimal working example
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/
Use event.preventDefault() inside user defined function
<form onsubmit="userFunction(event)"> ...
function userFunction(ev)
{
if(!event.target.send.checked)
{
console.log('form NOT submit on "Enter" key')
ev.preventDefault();
}
}
Open chrome console> network tab to see
<form onsubmit="userFunction(event)" action="/test.txt">
<input placeholder="type and press Enter" /><br>
<input type="checkbox" name="send" /> submit on enter
</form>
I used document on, which covers dynamically added html after page load:
$(document).on('keydown', '.selector', function (event) {
if (event.which == 13 || event.keyCode == 13) {
//do your thang
}
});
Added updates from #Bradley4