onkeypress event not firing in ie - javascript

$(".tbSearchBox").keyup(function (event) {
if (event.keyCode == 13) {
alert("ye");
searchSet = $(this).val();
$(".btnSerachButton").click();
}
});
Im using the above code to detect whether the user has typed something in a search box then hit enter instead of pressing the search button. this works for all browsers apart from IE. IE can read the on keyup event but bypasses the if statement used. Any idea why?

There some incompatibility in ie regarding event and keycode so to make it browser compatible try this
$(".tbSearchBox").keypress(function (event) {
var ev = event || window.event;
var key = ev.keyCode || ev.which || ev.charCode;
if (key == 13) {
ev.preventDefault();
alert("ye");
searchSet = $(this).val();
$(".btnSerachButton").click();
}
});

var code = (event.keyCode ? event.keyCode : event.which);
or maybe even
var code = event.keyCode || event.which;

You should use event.which here to normalise event.keyCode and event.charCode:
if (event.which == 13) ...

Related

keyCode for tab is not working

I am using the event keypress in backbone. The keyCode for Enter(13) works fine but the keyCode for tab(9) is not working for some odd reason. Please help me figure this out. Thanks.
onEnterSetTitle: function(ev) {
if (ev.keyCode === 9) {
this.$el.find('.set-title-input input').trigger('blur');
}
},
I fixed it by replace keypress with keydown.
if i have to do this then i would use || operator this way:
onEnterSetTitle: function(ev) {
var kc = ev.which || ev.keyCode;
if (kc === 9) {
.........
}
}

How to disable Windows keys (logo key and menu key) using Javascript

I write this Javascript code but it doesn't disable 2 windows keys (I mean logo key and menu key), though:
document.onkeydown = function(e) {
document.title = e.keyCode;
if (e.keyCode == 91 || e.keyCode == 93) {
window.event.keyCode = 0;
window.event.returnValue = false;
return false;
}
};
the 2 window.xxx statements are actually not necessary but I add them in to buy an insurance (Just doubt that e doesn't totally equal to window.event).
So I'd like to ask this question: " Is there a feasible way, directly or indirectly, to do this job in Javascript? "
Your code looks right, try to find out real keycodes with this simple script:
document.onkeydown = checkKeycode
function checkKeycode(e) {
var keycode;
if (window.event) keycode = window.event.keyCode;
else if (e) keycode = e.which;
alert("keycode: " + keycode);
}
And to disabel certain keys you modify function (example for 'Enter'):
document.onkeydown = checkKeycode
function checkKeycode(e) {
var event = e || window.event;
var keycode = event.which || event.keyCode;
if (keycode == 13) {
// return key was pressed
}
}
JavaScript cannot stop the effect of the Windows logo key, which (when released) is supposed to bring up the Window's start menu. In combination with other keys, it has other system wide effects (like with M = minimise all windows). This is something that happens outside of the browser context, and thus cannot and should not be blocked by the code running in your browser.
The Windows menu key can be somewhat disabled, as described in this answer:
$(function(){
var lastKey=0;
$(window).on("keydown", document, function(event){
lastKey = event.keyCode;
});
$(window).on("contextmenu", document, function(event){
if (lastKey === 93){
lastKey=0;
event.preventDefault();
event.stopPropagation();
return false;
}
});
});

Detect backspace and del on "input" event?

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>

How to listener the keyboard type text in Javascript?

I want to get the keyboard typed text, not the key code. For example, I press shift+f, I get the "F", instead of listen to two key codes. Another example, I click F3, I input nothing. How can I know that in js?
To do it document-wide, use the keypress event as follows. No other currently widely supported key event will do:
document.onkeypress = function(e) {
e = e || window.event;
var charCode = (typeof e.which == "number") ? e.which : e.keyCode;
if (charCode) {
alert("Character typed: " + String.fromCharCode(charCode));
}
};
For all key-related JavaScript matters, I recommend Jan Wolter's excellent article: http://unixpapa.com/js/key.html
I use jQuery to do something like this:
$('#searchbox input').on('keypress', function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if(code == 13) {
//Enter keycode
//Do something
}
});
EDIT: Since you're not binding to text box use:
$(window).on('keypress', function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if(code == 13) {
//Enter keycode
//Do something
}
});
http://docs.jquery.com/Main_Page
You can listen for the onkeypress event. However, instead of just examining either the event.keyCode (IE) or event.which (Mozilla) property which gives you the key code, you need to translate the key code using String.fromCharCode().
A good demo is at Javascript Char Codes (Key Codes). View the source and look for the displayKeyCode(evt) function.
Additional references: w3schools - onkeypress Event and w3schools - JavaScript fromCharCode() method.
This is too complicated to answer quickly. This is what I use as the definitive reference for keyboard handling. http://unixpapa.com/js/key.html

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