In my code, if you start typing your ermail in the form input and then use the down-arrow key to select an auto-suggest entry, and press ENTER, the function will trigger, even though I'm not pressing ENTER on the actual input.
function sysOnEnter(event) {
if (event.keyCode == 13) {
event.preventDefault();
console.log('key was enter');
}
}
<input type="text" name="email" onkeypress="sysOnEnter(event)">
After more research I managed to answer my own question.
function sysOnEnter(event, id) {
var key = event.key || event.keyCode;
if (key == 'Enter' || key == 13) {
var val = document.getElementById(id).value;
setTimeout(function() {
if (document.getElementById(id).value == val)
console.log('captured ENTER event');
},0);
event.preventDefault();
return false;
}
}
<input type="text" id="email" onkeypress="sysOnEnter(event, this.id)">
Related
I just want to detect the enter input keypress on my android device. I found out that using jquery, we can do like below:
$('#inputText').keypress(function(event) {
var keycode = event.keyCode || event.which;
if(keycode == '13') {
alert('You pressed a "enter" key in somewhere');
}
});
But I don't want to use jquery. I want to use the traditional way like using
document.getElementById('inputText')
But I don't know how to add in the keypress event function. Do you guys have any idea?
Almost the same as in jQuery. Use eventListener and pass an argument e to the function to catch the event and it's keyCode.
var elem = document.getElementById('inputText');
elem.addEventListener('keypress', function(e){
if (e.keyCode == 13) {
console.log('You pressed a "enter" key in somewhere');
}
});
<input id='inputText'>
document.getElementById("id").onKeyDown = function(event) {
if (event.keycode === 13) {
alert("return pressed");
}
};
Use event.key instead of event.keyCode!
const node = document.getElementById('inputText');
node.addEventListener('keydown', function onEvent(event) {
if (event.key === "Enter") {
// Do something
}
});
Mozilla Docs
Supported Browsers
You can use
document.getElementById('txtBox').onkeypress = function(e) {
if (!e) e = window.event;
var keyCode = e.keyCode || e.which;
if (keyCode == '13') {
alert("Enter Pressed");
}
}
<input id="txtBox" type="text" />
You can use addEventListener
document.getElementById('inputText').addEventListener("keypress", function() {});
Do this :
<form onsubmit="Search();" action="javascript:void(0);">
<input type="text" id="searchCriteria" placeholder="Search Criteria"/>
<input type="button" onclick="Search();" value="Search" id="searchBtn"/>
I am trying to disable a textarea from handling a keyboard event when ever a user presses the enter key of the keyboard when the textarea is empty using angularjs. I have been able to disable the submit button when the textarea is empty but I am trying to disable the textarea when from enter event when the textarea is empty.
This is my attempt:
<div class="descriptionarea">
<textarea ng-model="trackTxt" id="input" ></textarea>
<span class="buttonfortxtarea">
<button ng-disabled="!trackTxt" class= "btn btn-mini description_submit" id="new-chat-button">Submit</button></span>
</div>
When I hit enter from my textarea it triggers event using the following code
document.getElementById('input').addEventListener('keyup', function (e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13) { // enter key press
send();
}
});
The above code works whether the textarea is empty or not.
EDITTED:
In my app.js of angularjs
app.controller('TodoCtrl',function($scope){
//handle javascript enter event on key up
// function TodoCtrl($scope) {
$scope.trackTxt;
$scope.send = function($event){
alert('TEST');
}
$scope.isEmpty = function(param){
return param.trim().length === 0;
}
//}
});
In jsp file
<div ng-controller="TodoCtrl">
<textarea ng-keyup="$event.keyCode == 13 && !isEmpty(trackTxt) && send($event)" ng-model="trackTxt" id="input" ></textarea>
<span class="buttonfortxtarea">
<button ng-disabled="!trackTxt" ng-click="send($event)" class= "btn btn-mini description_submit" id="new-chat-button">Submit</button></span>
</div></div>
Please how can I use angularjs to prevent the enter event from happening when ever the text-area is empty.
You can use ng-keyup for attaching an function on enter key press,
ng-keyup="$event.keyCode == 13 && functionToCall()"
Here is demo,
Thanks
You could simply check if it's empty...
document.getElementById('input').addEventListener('keyup', function (e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13 && $(this).val() != "") { // enter key press
send();
}
});
This also may work:
document.getElementById('input').addEventListener('keyup', function (e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13 && $(this).val().length <= 0) { // enter key press
send();
}
});
To prevent the default enter use preventDefault() Event Method
document.getElementById('input').addEventListener('keyup', function (e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13 && $(this).val().length <= 0) { // enter key press
e.preventDefault(); //This avoid the enter...
}
});
How about the sendChat()...
document.getElementById('input').addEventListener('keyup', function (e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13 && $(this).val().length <= 0) { // enter key press
e.preventDefault(); //This avoid the enter...
}
else if(code == 13 && $(this).val().length > 0) {
sendChat();
}
});
I'm trying to implement a form with multiple buttons on it. When I press enter I want to have my default button submitted. This code from http://greatwebguy.com/programming/dom/default-html-button-submit-on-enter-with-jquery/ generally works:
$(function() {
$("form input").keypress(function (e) {
if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
$('button[type=submit].default').click();
return false;
} else {
return true;
}
});
});
but...
when I type in input field I have an autocomplete popup so when I press enter in this popup I expect to put this value to input field, not submit all form. Can I check somehow if this enter comes from popup? Or I should try to do this different way?
EDIT:
I think I didn't say it clear. This popup is not any part of jquery. It's standard popup that shows previously typed data into input. So it hasn't got any class nor id. Stop propagation doesn't work either. None of solutions below resolve this problem
You could use :visible to see if the dropdown div for the autocomplete is open, and then prevent the enter key action of your code completing. Something like this:
$("form input").keypress(function(e) {
var key = e.which || e.keyCode;
if (key == 13 && !$(".autocomplete").is(":visible")) {
e.preventDefault();
$('form').submit();
}
});
You could also use event.stopPropagation() on the enter key press in the autocomplete function, however you'll probably have to amend the source manually which isn't ideal.
Before return false;
write
e.preventDefault();
or/and
e.stopPropagation();
$("form input").keypress(function (e) {
if (e.target.id !== "autoCompliteId" && ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13))) {
$('button[type=submit].default').click();
return false;
} else {
return true;
}
});
I modified my code and it works now.
I have an enum called Operation in my command and I set different value of the field before every submit button eg:
<input type="submit" value="do sth" onclick="setOperationAndSubmit('DO_STH')"/>
<input type="submit" value="next" onclick="setOperationAndSubmit('DEFAULT')"/>
function setOperationAndSubmit(operation) {
if (document.myForm.elements['operation'].value === '') {
document.myForm.elements['operation'].value = operation;
}
document.myForm.submit();
}
Then I have my action that listens to keypress and it set appropriate operation on every enter key:
$(function() {
$("form input").keypress(function(e) {
if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
document.myForm.elements['operation'].value = 'DEFAULT';
}
});
});
so default action is executed when I press enter
How to do that?
I tried:
var key = event.which || event.keyCode || event.charCode;
if(key == 8) alert('backspace');
but it doesn't work...
If I do the same on the keypress event it works, but I don't want to use keypress because it outputs the typed character in my input field. I need to be able to control that
my code:
$('#content').bind('input', function(event){
var text = $(this).val(),
key = event.which || event.keyCode || event.charCode;
if(key == 8){
// here I want to ignore backspace and del
}
// here I'm doing my stuff
var new_text = 'bla bla'+text;
$(this).val(new_text);
});
no character should be appended in my input, besides what I'm adding with val()
actually the input from the user should be completely ignored, only the key pressing action is important to me
Use .onkeydown and cancel the removing with return false;. Like this:
var input = document.getElementById('myInput');
input.onkeydown = function() {
var key = event.keyCode || event.charCode;
if( key == 8 || key == 46 )
return false;
};
Or with jQuery, because you added a jQuery tag to your question:
jQuery(function($) {
var input = $('#myInput');
input.on('keydown', function() {
var key = event.keyCode || event.charCode;
if( key == 8 || key == 46 )
return false;
});
});
event.key === "Backspace"
More recent and much cleaner: use event.key. No more arbitrary number codes!
input.addEventListener('keydown', function(event) {
const key = event.key; // const {key} = event; ES6+
if (key === "Backspace" || key === "Delete") {
return false;
}
});
Mozilla Docs
Supported Browsers
With jQuery
The event.which property normalizes event.keyCode and event.charCode. It is recommended to watch event.which for keyboard key input.
http://api.jquery.com/event.which/
jQuery('#input').on('keydown', function(e) {
if( e.which == 8 || e.which == 46 ) return false;
});
It's an old question, but if you wanted to catch a backspace event on input, and not keydown, keypress, or keyup—as I've noticed any one of these break certain functions I've written and cause awkward delays with automated text formatting—you can catch a backspace using inputType:
document.getElementsByTagName('input')[0].addEventListener('input', function(e) {
if (e.inputType == "deleteContentBackward") {
// your code here
}
});
keydown with event.key === "Backspace" or "Delete"
More recent and much cleaner: use event.key. No more arbitrary number codes!
input.addEventListener('keydown', function(event) {
const key = event.key; // const {key} = event; ES6+
if (key === "Backspace" || key === "Delete") {
return false;
}
});
Modern style:
input.addEventListener('keydown', ({key}) => {
if (["Backspace", "Delete"].includes(key)) {
return false
}
})
Mozilla Docs
Supported Browsers
Have you tried using 'onkeydown'?
This is the event you are looking for.
It operates before the input is inserted and allows you to cancel char input.
$('div[contenteditable]').keydown(function(e) {
// trap the return key being pressed
if (e.keyCode === 13 || e.keyCode === 8)
{
return false;
}
});
InputEvent.inputType can be used for Backspace detection Mozilla Docs.
It works on Chrome desktop, Chrome Android and Safari iOS.
<input type="text" id="test" />
<script>
document.getElementById("test").addEventListener('input', (event) => {
console.log(event.inputType);
// Typing of any character event.inputType = 'insertText'
// Backspace button event.inputType = 'deleteContentBackward'
// Delete button event.inputType = 'deleteContentForward'
})
</script>
on android devices using chrome we can't detect a backspace.
You can use workaround for it:
var oldInput = '',
newInput = '';
$("#ID").keyup(function () {
newInput = $('#ID').val();
if(newInput.length < oldInput.length){
//backspace pressed
}
oldInput = newInput;
})
//Here's one example, not sure what your application is but here is a relevant and likely application
function addDashesOnKeyUp()
{
var tb = document.getElementById("tb1");
var key = event.which || event.keyCode || event.charCode;
if((tb.value.length ==3 || tb.value.length ==7 )&& (key !=8) )
{
tb.value += "-"
}
}
Live demo
Javascript
<br>
<input id="input">
<br>
or
<br>
jquery
<br>
<input id="inpu">
<script type="text/javascript">
var myinput = document.getElementById('input');
input.onkeydown = function() {
if (event.keyCode == 8) {
alert('you pressed backspace');
//event.preventDefault(); remove // to prevent backspace
}
if (event.keyCode == 46) {
alert('you pressed delete');
//event.preventDefault(); remove // to prevent delete
}
};
//jquery code
$('#inpu').on('keydown', function(e) {
if (event.which == 8) {
alert('you pressed backspace');
//event.preventDefault(); remove // to prevent backspace
}
if (event.which == 46) {
alert('you pressed delete');
//event.preventDefault(); remove // to prevent delete
}
});
</script>
I would like to detect whether the user has pressed Enter using jQuery.
How is this possible? Does it require a plugin?
It looks like I need to use the keypress() method.
Are there browser issues with that command - like are there any browser compatibility issues I should know about?
The whole point of jQuery is that you don't have to worry about browser differences. I am pretty sure you can safely go with enter being 13 in all browsers. So with that in mind, you can do this:
$(document).on('keypress',function(e) {
if(e.which == 13) {
alert('You pressed enter!');
}
});
I wrote a small plugin to make it easier to bind the "on enter key pressed" event:
$.fn.enterKey = function (fnc) {
return this.each(function () {
$(this).keypress(function (ev) {
var keycode = (ev.keyCode ? ev.keyCode : ev.which);
if (keycode == '13') {
fnc.call(this, ev);
}
})
})
}
Usage:
$("#input").enterKey(function () {
alert('Enter!');
})
I couldn't get the code posted by Paolo Bergantino to work, but when I changed it to $(document) and e.which instead of e.keyCode then I found it to work faultlessly.
$(document).keypress(function(e) {
if(e.which == 13) {
alert('You pressed Enter!');
}
});
Link to example on JS Bin
I found this to be more cross-browser compatible:
$(document).keypress(function(event) {
var keycode = event.keyCode || event.which;
if(keycode == '13') {
alert('You pressed a "enter" key in somewhere');
}
});
You can do this using the jQuery 'keydown' event handler:
$("#start").on("keydown", function(event) {
if(event.which == 13)
alert("Entered!");
});
Use event.key and modern JavaScript!
$(document).keypress(function(event) {
if (event.key === "Enter") {
// Do something
}
});
Or without jQuery:
document.addEventListener("keypress", function onEvent(event) {
if (event.key === "Enter") {
// Do something better
}
});
Mozilla documentation
Supported Browsers
I came up with this solution:
$(document).ready(function(){
$('#loginforms').keypress(function(e) {
if (e.which == 13) {
//e.preventDefault();
alert('login pressed');
}
});
$('#signupforms').keypress(function(e) {
if (e.which == 13) {
//e.preventDefault();
alert('register');
}
});
});
There's a keypress() event method. The Enter key's ASCII number is 13 and is not dependent on which browser is being used.
A minor extension of Andrea's answer makes the helper method more useful when you may also want to capture modified enter presses (i.e., Ctrl + Enter or Shift + Enter). For example, this variant allows binding like:
$('textarea').enterKey(function() {$(this).closest('form').submit(); }, 'ctrl')
to submit a form when the user presses Ctrl + Enter with focus on that form's textarea.
$.fn.enterKey = function (fnc, mod) {
return this.each(function () {
$(this).keypress(function (ev) {
var keycode = (ev.keyCode ? ev.keyCode : ev.which);
if ((keycode == '13' || keycode == '10') && (!mod || ev[mod + 'Key'])) {
fnc.call(this, ev);
}
})
})
}
(See also *Ctrl + Enter using jQuery in a TEXTAREA)
In some cases, you may need to suppress the ENTER key for a certain area of a page but not for other areas of a page, like the page below that contains a header <div> with a SEARCH field.
It took me a bit to figure out how to do this, and I am posting this simple yet complete example up here for the community.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Test Script</title>
<script src="/lib/js/jquery-1.7.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$('.container .content input').keypress(function (event) {
if (event.keyCode == 10 || event.keyCode == 13) {
alert('Form Submission needs to occur using the Submit button.');
event.preventDefault();
}
});
</script>
</head>
<body>
<div class="container">
<div class="header">
<div class="FileSearch">
<!-- Other HTML here -->
</div>
</div>
<div class="content">
<form id="testInput" action="#" method="post">
<input type="text" name="text1" />
<input type="text" name="text2" />
<input type="text" name="text3" />
<input type="submit" name="Submit" value="Submit" />
</form>
</div>
</div>
</body>
</html>
Link to JSFiddle Playground: The [Submit] button does not do anything, but pressing ENTER from one of the Text Box controls will not submit the form.
Try this to detect the Enter key pressed.
$(document).on("keypress", function(e){
if(e.which == 13){
alert("You've pressed the enter key!");
}
});
See demo # detect enter key press on keyboard
As the keypress event isn't covered by any official specification, the actual behavior encountered when using it may differ across browsers, browser versions, and platforms.
$(document).keydown(function(event) {
if (event.keyCode || event.which === 13) {
// Cancel the default action, if needed
event.preventDefault();
// Call function, trigger events and everything you want to do. Example: Trigger the button element with a click
$("#btn").trigger('click');
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<button id="btn" onclick="console.log('Button Pressed.')"> </button>
I used $(document).on("keydown").
On some browsers keyCode is not supported. The same with which so if keyCode is not supported you need to use which and vice versa.
$(document).on("keydown", function(e) {
const ENTER_KEY_CODE = 13;
const ENTER_KEY = "Enter";
var code = e.keyCode || e.which
var key = e.key
if (code == ENTER_KEY_CODE || key == ENTER_KEY) {
console.log("Enter key pressed")
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
$(document).keydown(function (event) {
//proper indentiation of keycode and which to be equal to 13.
if ( (event.keyCode || event.which) === 13) {
// Cancel the default action, if needed
event.preventDefault();
//call function, trigger events and everything tou want to dd . ex : Trigger the button element with a click
$("#btnsearch").trigger('click');
}
});
This my how I solved it. You should use return false;
$(document).on('keypress', function(e) {
if(e.which == 13) {
$('#sub_btn').trigger('click');
alert('You pressed the "Enter" key somewhere');
return false;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="" method="post" id="sub_email_form">
<div class="modal-header">
<button type="button" class="close" id="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Subscribe to our Technical Analysis</h4>
</div>
<div class="modal-body">
<p>Signup for our regular Technical Analysis updates to review recommendations delivered directly in your inbox.</p>
<div class="input-group">
<input type="email" name="sub_email" id="sub_email" class="form-control" placeholder="Enter your email" required>
</div>
<span id="save-error"></span>
</div>
<div class="modal-footer">
<div class="input-group-append">
<input type="submit" class="btn btn-primary sub_btn" id="sub_btn" name="sub_btn" value="Subscribe">
</div>
</div>
</form>
I think the simplest method would be using vanilla JavaScript:
document.onkeyup = function(event) {
if (event.key === 13){
alert("Enter was pressed");
}
}
The easy way to detect whether the user has pressed Enter is to use the key number. The Enter key number is equal to 13.
To check the value of key in your device:
$("input").keypress(function (e) {
if (e.which == 32 || (65 <= e.which && e.which <= 65 + 25)
|| (97 <= e.which && e.which <= 97 + 25)) {
var c = String.fromCharCode(e.which);
$("p").append($("<span/>"))
.children(":last")
.append(document.createTextNode(c));
} else if (e.which == 8) {
// Backspace in Internet Explorer only is on keydown
$("p").children(":last").remove();
}
$("div").text(e.which);
});
By pressing the Enter key, you will get result as 13. Using the key value, you can call a function or do whatever you wish:
$(document).keypress(function(e) {
if(e.which == 13) {
console.log("The user pressed the Enter key");
// The code you want to run
}
});
If you want to target a button once the Enter key is pressed, you can use the code:
$(document).bind('keypress', function(e) {
if(e.which === 13) { // Return
$('#buttonname').trigger('click');
}
});
$(document).keyup(function(e) {
if(e.key === 'Enter') {
//Do the stuff
}
});
$(function(){
$('.modal-content').keypress(function(e){
debugger
var id = this.children[2].children[0].id;
if(e.which == 13) {
e.preventDefault();
$("#"+id).click();
}
})
});