keypress event not generated in Chrome on ENTER Key? - javascript

My application requires an input from users, on entering a value in a textbox, users hit Enter (Return Key) and this calls a
buttons onclick event. This works fine in IE, FF but not Chrome. On enter in chrome, keypress event is not generated
Here is my code snippet
$('#myDiv').keypress(function (e) {
alert("Key pressed");
if (e.keyCode == $.ui.keyCode.ENTER) {
alert("enter pressed");
}
});
Could anyone provide input on this?

Cross-browsers method :
$('#myDiv').keydown( function(e) {
var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
if(key == 13) {
e.preventDefault();
alert("enter pressed");
}
});
Tested on Chrome 24 : http://jsfiddle.net/PTauw/1/

keypress is the correct event for detecting which character has been typed (although in this particular case, that of detecting the enter key, keydown would work just as well). However, how to get the character typed in a keypress event is inconsistent between browsers, so jQuery normalizes on the which property. Here's what you want:
$('#myDiv').keypress(function (e) {
alert("Key pressed");
if (e.which == $.ui.keyCode.ENTER) {
alert("enter pressed");
}
});
The definitive reference for key events: http://unixpapa.com/js/key.html

This link might be helpful for you...
Api Jquery Key Press
or try with this code
Change keypress to keydown:
$('#myDiv').keydown(function(e) {
// your logic
alert("Key pressed");
if (e.keyCode == $.ui.keyCode.ENTER) {
alert("enter pressed");
}
});

Chrome seems to be working with ENTER key and not 13.
this works for me on all browsers including CHROME.
$('#myDiv').keydown(function(e) {
if ((e.which == 13) || (e.which == keyCode.ENTER)) {
alert("enter pressed");
}

Related

How to submit the form when pressing Ctrl + S (instead of "save the webpage") in JavaScript? [duplicate]

How do I go about capturing the CTRL + S event in a webpage?
I do not wish to use jQuery or any other special library.
Thanks for your help in advance.
An up to date answer in 2020.
Since the Keyboard event object has been changed lately, and many of its old properties are now deprecated, here's a modernized code:
document.addEventListener('keydown', e => {
if (e.ctrlKey && e.key === 's') {
// Prevent the Save dialog to open
e.preventDefault();
// Place your code here
console.log('CTRL + S');
}
});
Notice the new key property, which contains the information about the stroked key. Additionally, some browsers might not allow code to override the system shortcuts.
If you're just using native / vanilla JavaScript, this should achieve the results you are after:
var isCtrl = false;
document.onkeyup=function(e){
if(e.keyCode == 17) isCtrl=false;
}
document.onkeydown=function(e){
if(e.keyCode == 17) isCtrl=true;
if(e.keyCode == 83 && isCtrl == true) {
//run code for CTRL+S -- ie, save!
return false;
}
}
What's happening?
The onkeydown method checks to see if it is the CTRL key being pressed (key code 17).
If so, we set the isCtrl value to true to mark it as being activated and in use. We can revert this value back to false within the onkeyup function.
We then look to see if any other keys are being pressed in conjunction with the ctrl key. In this example, key code 83 is for the S key. You can add your custom processing / data manipulation / save methods within this function, and we return false to try to stop the browser from acting on the CTRL-S key presses itself.
document.onkeydown = function(e) {
if (e.ctrlKey && e.keyCode === 83) {
alert('hello there');
// your code here
return false;
}
};
You need to replace document with your actual input field.
DEMO
document.onkeydown = function(e) {
if (e.ctrlKey && e.keyCode === 83) {
alert('strg+s');
}
return false;
};
Some events can't be captured, since they are capture by the system or application.
Oops you wanted simultaneous, changed code to reflect your scenario
function iskeyPress(e) {
e.preventDefault();
if (e.ctrlKey&&e.keyCode == 83) {
alert("Combination pressed");
}
return false;//To prevent default behaviour
}
Add this to body
<body onkeyup="iskeypress()">
Mousetrap is a great library to do this (8,000+ stars on Github).
Documentation: https://craig.is/killing/mice
// map multiple combinations to the same callback
Mousetrap.bind(['command+s', 'ctrl+s'], function() {
console.log('command s or control s');
// return false to prevent default browser behavior
// and stop event from bubbling
return false;
});
Add Shortcuts JS library and do the following code :
<script src="js/libs/shortcut/shortcut.js" type="text/javascript"></script>
Then
shortcut.add("Ctrl+S", function() {
alert("لقد قمت بالصغط على مراقبة مع حرف السين");
});

Overriding shortcut keys in Firefox and Chrome

I have a script that is supposed to open a section of a web page, and save changes on Ctrl + n and Ctrl + s respectively. I got it working in IE, but it doesn't seem to work in Firefox and Chrome. Any ideas?
My override function.
function prevent(e)
{
try{e.stopPropagation();}catch(ex){}
try{e.preventDefault()}catch(ex){}
try{if (e.preventDefault)
e.preventDefault();
else {
e.cancelBubble = true;
e.returnValue = false;
e.keyCode = 0;
}} catch(ex){}
}
I have seen the same issue. Some browsers will not allow you to capture certain shortcuts. Look at this https://stackoverflow.com/a/7296303/1366887
Some key combinations are resticted in Chrome 4, but not in Chrome 3. Look here: https://groups.google.com/a/chromium.org/forum/?fromgroups=#!topic/chromium-bugs/Ntc1byZXHfU
Here is the Javascript:
$(window).keydown(function(event) {
if(event.ctrlKey && event.keyCode == 84) {
console.log("Hey! Ctrl+T event captured!");
event.preventDefault();
}
if(event.ctrlKey && event.keyCode == 83) {
console.log("Hey! Ctrl+S event captured!");
event.preventDefault();
}
});
I have used this numerous times, and it has worked greatly.
Here is another rescource you can take a look at: http://unixpapa.com/js/key.html
Without Jquery:
onkeydown = function(e){
if(e.ctrlKey && e.keyCode == 'S'.charCodeAt(0)){
e.preventDefault();
//your saving code
}
}
Here is a JSFIDDLE of it working.
For anyone looking for this in the future, the answer for current browsers is the following:
if (event.ctrlKey && event.key === 'k') event.preventDefault()

phonegap tel softkeyboard done action

i try to bind an event to done action on soft keyboard tell mode.
but i can't catch any event.
i tried use keyup/ keydown, blur and change events.
nothing happened in iPhone and android.
$("input").bind('keyup', function(event){
var key;
if(window.event)
key = window.event.keyCode;
else
key = event.which;
if(key == 13 || key == 10){
alert(key);
}
});
$("input").bind('blur', function(event){
alert("blur");
});
$("input").bind('change', function(event){
alert("change");
});
Any solution?
You are missing a close } after the one if.
Also, maybe the selector you are using $('input') is too broad try something specific, i use somelike like this:
$('#element_id').live('keypress',function(e){
console.log('keypress: '+e.keyCode);
if (e.keyCode != 13) {
console.log('is not an enter key');
}
else {
console.log('is an enter key going to submit');
Fling.poo();
return false;
}
});

javascript keypress enter key

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.
}

How to detect escape key press with pure JS or jQuery?

Possible Duplicate:
Which keycode for escape key with jQuery
How to detect escape key press in IE, Firefox and Chrome?
Below code works in IE and alerts 27, but in Firefox it alerts 0
$('body').keypress(function(e){
alert(e.which);
if(e.which == 27){
// Close my modal window
}
});
Note: keyCode is becoming deprecated, use key instead.
function keyPress (e) {
if(e.key === "Escape") {
// write your logic here.
}
}
Code Snippet:
var msg = document.getElementById('state-msg');
document.body.addEventListener('keypress', function(e) {
if (e.key == "Escape") {
msg.textContent += 'Escape pressed:'
}
});
Press ESC key <span id="state-msg"></span>
keyCode is becoming deprecated
It seems keydown and keyup work, even though keypress may not
$(document).keyup(function(e) {
if (e.key === "Escape") { // escape key maps to keycode `27`
// <DO YOUR WORK HERE>
}
});
Which keycode for escape key with jQuery
The keydown event will work fine for Escape and has the benefit of allowing you to use keyCode in all browsers. Also, you need to attach the listener to document rather than the body.
Update May 2016
keyCode is now in the process of being deprecated and most modern browsers offer the key property now, although you'll still need a fallback for decent browser support for now (at time of writing the current releases of Chrome and Safari don't support it).
Update September 2018
evt.key is now supported by all modern browsers.
document.onkeydown = function(evt) {
evt = evt || window.event;
var isEscape = false;
if ("key" in evt) {
isEscape = (evt.key === "Escape" || evt.key === "Esc");
} else {
isEscape = (evt.keyCode === 27);
}
if (isEscape) {
alert("Escape");
}
};
Click me then press the Escape key
Using JavaScript you can do check working jsfiddle
document.onkeydown = function(evt) {
evt = evt || window.event;
if (evt.keyCode == 27) {
alert('Esc key pressed.');
}
};
Using jQuery you can do check working jsfiddle
jQuery(document).on('keyup',function(evt) {
if (evt.keyCode == 27) {
alert('Esc key pressed.');
}
});
check for keyCode && which & keyup || keydown
$(document).keydown(function(e){
var code = e.keyCode || e.which;
alert(code);
});
Pure JS
you can attach a listener to keyUp event for the document.
Also, if you want to make sure, any other key is not pressed along with Esc key, you can use values of ctrlKey, altKey, and shifkey.
document.addEventListener('keydown', (event) => {
if (event.key === 'Escape') {
//if esc key was not pressed in combination with ctrl or alt or shift
const isNotCombinedKey = !(event.ctrlKey || event.altKey || event.shiftKey);
if (isNotCombinedKey) {
console.log('Escape key was pressed with out any group keys')
}
}
});
pure JS (no JQuery)
document.addEventListener('keydown', function(e) {
if(e.keyCode == 27){
//add your code here
}
});
Below is the code that not only disables the ESC key but also checks the condition where it is pressed and depending on the situation, it will do the action or not.
In this example,
e.preventDefault();
will disable the ESC key-press action.
You may do anything like to hide a div with this:
document.getElementById('myDivId').style.display = 'none';
Where the ESC key pressed is also taken into consideration:
(e.target.nodeName=='BODY')
You may remove this if condition part if you like to apply to this to all. Or you may target INPUT here to only apply this action when the cursor is in input box.
window.addEventListener('keydown', function(e){
if((e.key=='Escape'||e.key=='Esc'||e.keyCode==27) && (e.target.nodeName=='BODY')){
e.preventDefault();
return false;
}
}, true);
Best way is to make function for this
FUNCTION:
$.fn.escape = function (callback) {
return this.each(function () {
$(document).on("keydown", this, function (e) {
var keycode = ((typeof e.keyCode !='undefined' && e.keyCode) ? e.keyCode : e.which);
if (keycode === 27) {
callback.call(this, e);
};
});
});
};
EXAMPLE:
$("#my-div").escape(function () {
alert('Escape!');
})
On Firefox 78 use this ("keypress" doesn't work for Escape key):
function keyPress (e)(){
if (e.key == "Escape"){
//do something here
}
document.addEventListener("keyup", keyPress);
i think the simplest way is vanilla javascript:
document.onkeyup = function(event) {
if (event.keyCode === 27){
//do something here
}
}
Updated: Changed key => keyCode

Categories

Resources