Detect backspace and del on "input" event? - javascript

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>

Related

How I can detect Key "Enter" on "input" event? [duplicate]

I'm trying to do a function if enter is pressed while on specific input.
What I'm I doing wrong?
$(document).keyup(function (e) {
if ($(".input1").is(":focus") && (e.keyCode == 13)) {
// Do something
}
});
Is there a better way of doing this which would say, if enter pressed on .input1 do function?
$(".input1").on('keyup', function (e) {
if (e.key === 'Enter' || e.keyCode === 13) {
// Do something
}
});
// e.key is the modern way of detecting keys
// e.keyCode is deprecated (left here for for legacy browsers support)
// keyup is not compatible with Jquery select(), Keydown is.
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("input1")[0];
node.addEventListener("keyup", function(event) {
if (event.key === "Enter") {
// Do work
}
});
Modern style, with lambda and destructuring
node.addEventListener("keyup", ({key}) => {
if (key === "Enter") {
// Do work
}
})
If you must use jQuery:
$(document).keyup(function(event) {
if ($(".input1").is(":focus") && event.key == "Enter") {
// Do work
}
});
Mozilla Docs
Supported Browsers
$(document).keyup(function (e) {
if ($(".input1:focus") && (e.keyCode === 13)) {
alert('ya!')
}
});
Or just bind to the input itself
$('.input1').keyup(function (e) {
if (e.keyCode === 13) {
alert('ya!')
}
});
To figure out which keyCode you need, use the website http://keycode.info
Try this to detect the Enter key pressed in a textbox.
$(function(){
$(".input1").keyup(function (e) {
if (e.which == 13) {
// Enter key pressed
}
});
});
The best way I found is using keydown ( the keyup doesn't work well for me).
Note: I also disabled the form submit because usually when you like to do some actions when pressing Enter Key the only think you do not like is to submit the form :)
$('input').keydown( function( event ) {
if ( event.which === 13 ) {
// Do something
// Disable sending the related form
event.preventDefault();
return false;
}
});
It may be too late to answer this question. But the following code simply prevents the enter key. Just copy and paste should work.
<script type="text/javascript">
function stopRKey(evt) {
var evt = (evt) ? evt : ((event) ? event : null);
var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
if ((evt.keyCode == 13) && (node.type=="text")) {return false;}
}
document.onkeypress = stopRKey;
</script>
The solution that work for me is the following
$("#element").addEventListener("keyup", function(event) {
if (event.key === "Enter") {
// do something
}
});
Try this to detect the Enter key pressed in a textbox.
$(document).on("keypress", "input", function(e){
if(e.which == 13){
alert("Enter key pressed");
}
});
DEMO
A solution that worked for me is this:
<input onkeydown="if (event.key == 'Enter'){//do logic}else{}">
$(document).ready(function () {
$(".input1").keyup(function (e) {
if (e.keyCode == 13) {
// Do something
}
});
});
This code handled every input for me in the whole site. It checks for the ENTER KEY inside an INPUT field and doesn't stop on TEXTAREA or other places.
$(document).on("keydown", "input", function(e){
if(e.which == 13){
event.preventDefault();
return false;
}
});
Here is what I did for my angular project:
HTML:
<input
class="form-control"
[(ngModel)]="searchFirstName"
(keyup)="keyUpEnter($event)"
/>
TypeScript:
keyUpEnter(event: KeyboardEvent) {
if (event.key == 'Enter') {
console.log(event);
}
}

JavaScript/JQuery - Detect Shift + Tab with blur() event

there is a input where blur() event is trigger, and this input, i want to detect if was triggered with a Tab key, shift+tab keys or a click out. Detecting with just Tab key and click out, i've got. But the Shift+Tab keys, i couldn't. i've tried detect with window.event.shiftKey, or using on() of JQuery's method, and attach keyup, keydown, keypress to see if detect one first of the other. But, was unsuccessful. How can i detect this ?
I built these codes, but no one works:
1.
var shift_key; var key = window.event.keyCode;
$("#address").on('focusout blur keyup keydown keypress',function(e){
if(e.type == 'keyup' || e.type == 'keydown' || e.type == 'keypress'){
if(key == 16){
shift_key = true;
}
}else if((e.type == 'focusout' || e.type == 'blur') && key == 9){
if(shift_key == true){
document.getElementById('city').focus();
}
}
});
(This one, i tried to catch one the Shift code and after the Tab code. 'Cause when triggers a key event he doesn't blur of the input, so, i tried to catch in keyup, keydown or keypress the Shift key. And when the Tab were pressed, it automatically blur of the input, so, i tried to catch the Tab key)
$("#address").on("keyup keydown keypress", function () {
var shift_key = key;
setTimeout(function(){
$("#address").on("blur focusout", function () {
var shift_key = key;
});
}, 400);
});
This maybe what you want will detect which type of event was used to leave the input.
$("#z").on('keydown blur', function(e) {
if (e.shiftKey && e.keyCode === 9) {
console.log('shift tab')
return false;
} else if (e.keyCode === 9) {
console.log('tab')
return false;
} else if(e.type == 'blur') {
console.log('mosueOUt')
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="z" />
Maybe something like this is what you are looking for?
var tabKey = false,
shiftKey = false;
$('#input').on('blur', function(e) {
if(tabKey) {
if(shiftKey) {
console.log('Blurred by shift + tab');
}
else {
console.log('Blurred by tab');
}
}
else {
console.log('Blurred by mouse');
}
tabKey = shiftKey = false;
});
$('#input').on('keydown', function(e) {
tabKey = e.which === 9 ? true : false;
shiftKey = e.shiftKey;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="input" />
You don't need to store the shift key. You can use e.shiftKey
$("#address").on('focusout blur keyup keydown keypress',function(e){
if(e.type == 'keyup' || e.type == 'keydown' || e.type == 'keypress'){
/*
if(key == 16){
shift_key = true;
}
*/
}else if((e.type == 'focusout' || e.type == 'blur') && e.key == 9){
if(e.shiftKey){
document.getElementById('city').focus();
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Address
<input id="address" />
City
<input id="city" />

HTML form focus

How do i simulate enter key pressed to behave like tab. I would not like to use jQuery. I simply need to blur(loose focus) on current input (textfield) and focus on next (input) element. I tried this but it doesn´t work.
const handleKeyUp = (event) => {
const keyCode = event.keyCode || event.which;
if (event.target.value !== '' && keyCode === 13) {
event.preventDefault();
event.target.blur();
event.target.dispatchEvent(new KeyboardEvent('keypress', { key: 'Tab' }));
}
};
You can't trigger default browser behaviour by simulating events.
You'll need to identify the next field in the tab order, find it in the DOM, then call its focus() method.
$(document).on('keydown', ':tabbable', function (e) {
if (e.which == 13 || e.keyCode == 13 ) {
e.preventDefault();
var $canfocus = $(':tabbable:visible')
var index = $canfocus.index(document.activeElement) + 1;
if (index >= $canfocus.length) index = 0;
$canfocus.eq(index).focus();
}
});
Example

Javascript onkeydown percent or five number

Is there any way to find out if the user pressed the percent key or 5 number? It has the same keycode in FireFox.
You can check for modifier keys provided by the event object. event.shiftKey is for your specific use case. In addition there are the event.altKey, event.ctrlKey and event.metaKey (for windows key in windows and command key in MAC keyboards) properties of the event.
In a code example you would have to perform the check inside your keyCode handler:
var NUMBER_FIVE = 53;
element.onkeydown = function (event) {
if (event.keyCode == NUMBER_FIVE) {
if (event.shiftKey) {
// '%' handler
} else {
// '5' handler
}
}
};
In addition when using event.keyCode you are handling what the user pressed on the keyboard. If you want to be checking for specific ASCII characters then you can use event.charCode instead because this event property tells you what character the user is inputting instead of telling you what the user is pressing on the keyboard. Here's a complete guide for this on quirksmode.
If you use keydown, 5 and % are the same keyCode. The event object also has a shiftKey boolean property that will tell you if the user is holding shift.
document.onkeydown = function (e) {
if (e.keyCode === 53) {
if (e.shiftKey) {
// they pressed %
} else {
// they pressed 5
}
}
};
If you want to use keypress, they are two different keyCodes:
document.onkeypress = function (e) {
if (e.keyCode === 53) {
// they pressed 5
}
if (e.keyCode === 37) {
// they pressed %
}
};
This site is good for testing keyCodes.
Checking shiftKey value: jsfiddle
$(document).keydown(function(e){
if( e.keyCode == 53 ){
if(e.shiftKey){
// % pressed
}
else{
// 5 pressed
}
}
});​
I test for both the keyCode and the value of the character being entered.
$(document).on({
keypress: function(event){
var charCode = (event.which) ? event.which : event.keyCode;
var mFive = String.fromCharCode(event.which);
if ((charCode == 53) && (mFive === "5")){
return true;
}else if ((charCode == 53) && (mFive !== "5")){
return false;
}
});

onkeypress event not firing in ie

$(".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) ...

Categories

Resources