javascript keypress enter key - javascript

I have an input field <input type="text" name="input" /> outside of a form so that it is not submit when the user presses enter. I want to know when the user presses enter without submitting so that I can run some JavaScript. I want this to work in all major browsers (I don't care about IE though) and be valid JavaScript.
FYI: jQuery is an option

I will not use jQuery and this is going to work in IE < 9 too. With jQuery or other frameworks you may have some simpler ways to attach event listeners.
var input = document.getElementsByName("input")[0];
if (input.addEventListener)
input.addEventListener("keypress", function(e) {
if (e.keyCode === 13) {
// do stuff
e.preventDefault();
}
}, false);
else if (input.attachEvent)
input.attachEvent("onkeypress", function(e) {
if (e.keyCode === 13) {
// do stuff
return e.returnValue = false;
}
});

$("input[name='input']").keypress(function(e) {
//13 maps to the enter key
if (e.keyCode == 13) {
doSomeAwesomeJavascript();
}
})
function doSomeAwestomeJavascript() {
//Awesome js happening here.
}

Related

ie11 Detecting Enter Key pressed

I have the following piece of code in an asp mvc page
$('#regForm').submit(function (event) {
if (event.keyCode == '13') {
event.preventDefault();
}
});
The aim is to prevent the form from submitting when enter is pressed.
We have noticed that in ie 11, this is not working, and on stepping into the code via debug, event.keycode is null. I have been doing some researching on this, and it seems to be an issue because we have the IE-8 Compatibility Meta Tag present on the page, which means that event.keyCode (and event.which) returns undefined for the event, and so my form is always submitted.
So how do I rewrite this to get round the issue?
You need to use the keypress event, not form submit
$('#regForm').keypress(function (event) {
if (event.keyCode == 13) {
event.preventDefault();
}
});
Try something like this, use window.event:
$('#regForm').submit(function (e) {
var keyCode = (window.event) ? e.which : e.keyCode;
if (keyCode == '13') {
e.preventDefault();
}
});
Use type="button" attribute with <button> element
So that IE thinks the button as a simple button instead of a submit button.
So form will not submit
You can also get more details from below url
http://tjvantoll.com/2013/01/01/enter-should-submit-forms-stop-messing-with-that/
$('#regForm').keypress((event) => {
if (event.key === "Enter") {
event.preventDefault();
}
});

jQuery disabling submit-by-press on keyboard

I want to disable the "Enter" button on the keyboard so that when the user press enter to submit the form, nothing happens, and doing something else rather than submitting the form, such as alerting "Using keyboard is not allowed."
Here is what I have done, #calculator is a button:
$(document).ready(function(){
$("#calculator").keydown(function(){
console.log("Enter is disabled.");
return false;
});
});
Currently on its submission the form results unexpectedly (for instance redirects to the target page but without any CSS loaded.
$(document).on('keypress', function(e){
if(e.which == 13) {
e.preventDefault();
}
});
You can use .keypress() event to check which key was pressed then check the code of the key using e.keycode or e.which, if it's 13 then prevent submitting form:
$(document).keypress(function(e){
var code = e.keyCode || e.which;
if (code == 13 ) {
e.preventDefault();
return false;
}
});
For it, don't use submit button.
Use a div, style it like a button and submit the form using javascript on click of the div :)
Try this
For Disabling Keyboard
document.onkeydown = function (e) {
alert('Using keyboard is not allowed')
}
For Disabling Enter
$(document).on('keypress', function(e){
if(e.which == 13) {
e.preventDefault();
}
});

How to prevent ENTER key to change line in web form

I want to submit the form by press the ENTER key.
But it also change the line in content.
How to prevent this?
This is my code, but when hit ENTER, the ... run and Cursor moved to the next line:
function postmessage(e) {
if(e) {
e.preventDefault = null || e.preventDefault;
if(e.preventDefault) {
e.preventDefault();
} else {
e.returnValue = false;
}
}
....
return false;
}
function submitmessage(e) {
if(e.keyCode == 13) {
postmessage(e);
}
return false;
}
function bindEvent(el, eventName, eventHandler) {
if (el.addEventListener){
el.addEventListener(eventName, eventHandler, false);
} else if (el.attachEvent){
el.attachEvent('on'+eventName, eventHandler);
}
}
bindEvent(text, 'keydown', submitmessage);
Generally it is a bad idea to screw around with default behavior of the browser. Personally I would hate it if I was typing in some text, hit enter and bam, without a proper review of my data it get's submitted?!
If you don't want people to enter multiple lines in a textarea, why not make it a regular textbox (<input type="text" />)?
While I completely agree with #Peter in that this will create a very awkward and annoying user experience, here's how to achieve it code-wise: Capture the event on a keydown, and bypass the newline with event.preventDefault(). Then manually submit your form.
Something like this:
var el = document.getElementById('#my_textarea');
if (el.addEventListener)
{
el.addEventListener('keydown', checkEnter(event), false);
}
else if (el.attachEvent){
el.attachEvent('keywodn', checkEnter(event));
}
function checkEnter(event)
{
var charCode = (event.which) ? event.which : event.keyCode
// Enter key
if(charCode == 13) {
event.preventDefault();
document.myform.submit();
return false;
}
}
MDN Docs:
https://developer.mozilla.org/en/DOM/event.preventDefault
https://developer.mozilla.org/en/DOM/element.addEventListener
e.stopPropagation(); stopped the default action.

JSF: How to submit the form when the enter key is pressed?

It would appear to be a simple requirement, but I haven't found a simple solution yet:
In a JSF 1.2 / Richfaces 3.3 webapp, I have a form with input components of various types, followed by an <a4j:commandButton> and a <h:commandButton>. The former resets the form, the second performs some action with the data entered.
My goal is to have this action triggered when the user presses the enter key while entering data. How can I do that?
Edit: Generally, I have more than one <h:commandButton> per <form>. I'd like to designate a particular one as default action. Also, I'd like the solution to play nice with AJAX (which we use extensively).
Unless you are using MSIE browser and in reality you've only one input field without a button, it should just be the default behaviour. Otherwise probably some (autogenerated) JS code has messed it up.
If you don't have textareas in the form, an easy fix would be the following:
<h:form onkeypress="if (event.keyCode == 13) submit();">
Or if you have textareas and you don't want to repeat the same keypress functions over all non-textarea input elements, run the following script during window onload.
for (var i = 0; i < document.forms.length; i++) {
var inputs = document.forms[i].getElementsByTagName('input');
for (var j = 0; j < inputs.length; j++) {
inputs[j].onkeypress = function(e) {
e = e || window.event;
if (event.keyCode == 13) {
this.form.submit();
return false;
}
};
}
}
Building on BalusC's answer I came up with the following (tested on IE and FireFox):
<h:form id="form" onkeypress="ifEnterClick(event, #{rich:element('searchButton')});">
where ifEnterClick is defined by:
/**
* Handler for onkeypress that clicks {#code targetElement} if the
* enter key is pressed.
*/
function ifEnterClick(event, targetElement) {
event = event || window.event;
if (event.keyCode == 13) {
// normalize event target, so it looks the same for all browsers
if (!event.target) {
event.target = event.srcElement;
}
// don't do anything if the element handles the enter key on its own
if (event.target.nodeName == 'A') {
return;
}
if (event.target.nodeName == 'INPUT') {
if (event.target.type == 'button' || event.target.type == 'submit') {
if (strEndsWith(event.target.id, 'focusKeeper')) {
// inside some Richfaces component such as rich:listShuttle
} else {
return;
}
}
}
if (event.target.nodeName =='TEXTAREA') {
return;
}
// swallow event
if (event.preventDefault) {
// Firefox
event.stopPropagation();
event.preventDefault();
} else {
// IE
event.cancelBubble = true;
event.returnValue = false;
}
targetElement.click();
}
}
Edit: Since selecting a value from Firefox form auto completion using the enter key fires a keydown event, but no keypress event, using onkeypress is preferable to onkeydown.
Just put this code in your JS file:
$('input,textarea').live('keydown',function(e) { // submit forms on pressing enter while focus is on any input elmnt inside form
if (e.keyCode == 13) {
$(this).closest('form').submit();
}
});
In retrospect, solving this problem with the means HTML provides is far less brittle and easier to maintain, as the answers to the following related question show:
Multiple submit buttons on HTML form – designate one button as default
Use the PrimeFaces component:
<!-- Default button when pressing enter -->
<p:defaultCommand target="submit"/>
Use this in combination with a focus component and you will rock!
<!-- Focus on first field, or first field with error -->
<p:focus context="feesboek"/>

Prevent form submission on Enter key press

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

Categories

Resources