disable enter key on page, but NOT in textarea - javascript

Found this script:
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;
Only issue, it also stops enter key being used in textarea. Which is a hassle.
I have toyed with using:
onkeypress="return handleEnter(this, event)"
But our forms are extremely complex, and I am looking for a cleaner way of doing things.

You need to check the nodeName or tagName of the event target here, like this:
if (evt.keyCode == 13 && node.nodeName != "TEXTAREA") { return false; }
I noticed after this was accepted that you are already using jQuery, you can just replace all your code above with this:
$(document).keypress(function (e) {
if(e.which == 13 && e.target.nodeName != "TEXTAREA") return false;
});

I think you can just change this line
if (evt.keyCode == 13 && node.type == "text") {
return false;
}
to
if (evt.keyCode == 13 && node.type != "TEXTAREA") {
return false;
}

If you use jquery (highly recommended) then this will automatically add the function to allow use of the enter key:
$("textarea").focus(function () {
$(this).keypress(handleEnter);
});

Related

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" />

Prevent backspace from navigating back in AngularJS

I faced this issue in my AngularJS webapp.
When a user enters a page with a form to fill and he starts typing, if he presses the backspace key and the focus is not on the input text, then the page goes to the previous state.
I looked up this solution using jQuery, but it doesn't seem the appropiate way for achieve this in AngularJS.
There is $document in angular js:
angular.module('yourModule', [])
.controller('yourController', ['$scope', '$document', function($scope, $document) {
$document.on('keydown', function(e){
if(e.which === 8 && ( e.target.nodeName !== "INPUT" && e.target.nodeName !== "SELECT" ) ){ // you can add others here inside brackets.
e.preventDefault();
}
});
}
]);
Plnkr Demo.
You can see in the demo i have used only for "INPUT" nodeName and it does not prevent the default of the backspace key on text input but not on textarea because we have not handled it in the condition.
I can't comment "accepted answer", but it will work not right, as condition
e.which === 8 && e.target.nodeName !== "INPUT" || e.target.nodeName !== "SELECT"
with logic error, so you can use
e.which === 8 && e.target.nodeName !== "INPUT" && e.target.nodeName !== "SELECT"
or answer that wrote #ThisIsMarkSantiago.
Add the below script in your controller
var rx = /INPUT|SELECT|TEXTAREA/i;
$document.on("keydown keypress", function(e){
if( e.which == 8 ){ // 8 == backspace
if(!rx.test(e.target.tagName) || e.target.disabled || e.target.readOnly ){
e.preventDefault();
}
}
});
Or you can use Jquery
$(function(){
var regx = /INPUT|SELECT|TEXTAREA/i;
$(document).bind("keydown keypress", function(e){
if( e.which == 8 ){ // 8 == backspace
if(!regx.test(e.target.tagName) || e.target.disabled || e.target.readOnly ){
e.preventDefault();
}
}
});
});
I got this answer here:
How can I disabling backspace key press on all browsers?
$(document).keydown(function(e) {
var nodeName = e.target.nodeName.toLowerCase();
if (e.which === 8) {
if ((nodeName === 'input' && e.target.type === 'text') ||
nodeName === 'textarea') {
// do nothing
} else {
e.preventDefault();
}
}
});
Just put it inside your controller.

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>

Know if input is in use and disable the hotkey (Jquery)

I use some hotkeys on my website, but when the user is inside the search form or inside comment. I want to disable them.
What the best for me to do it? Thanks
Example of my hotkey:
$(document).keydown(function(e)
{
if (e.which == 40 || e.which == 74) // next post
{
return scroll('next');
}
if (e.which == 38 || e.which == 75) // prev post
{
return scroll('prev');
}
});
You can check for the event.target element. If that element is from type INPUT you might want to omit the handler code. Could look like
$(document).keydown(function(e)
{
if( e.target.nodeName !== 'INPUT' ) {
if (e.which == 40 || e.which == 74) // next post
{
return scroll('next');
}
if (e.which == 38 || e.which == 75) // prev post
{
return scroll('prev');
}
}
});
You could check if e.target.nodeName === INPUT (the event is triggered inside an input field) and act accordingly

Why isnt page stopping the keypress?

I have placed the following code at the top of my page in the head:
<script type="text/javascript">
function stopRKey(evt) {
console.log(evt.keyCode);
var evt = (evt) ? evt : ((event) ? event : null);
var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
console.log(evt.keyCode);
if ((evt.keyCode == 13) && (node.type == "text")) {
return false;
}
}
document.onkeypress = stopRKey;
</script>
On one of my pages it is not firing the event when I hit enter. But only one one of my pages the reast seem to work and log a keycode of 13 thus stopping the postback.
Any ideas why this event wouldnt be firing on this certain page?
Cheers,
Pete
You can certainly simplify the code. There's no reason why this shouldn't work, for <input type="text"> elements:
function stopRKey(evt) {
evt = evt || window.event;
var node = evt.target || evt.srcElement;
console.log(evt.keyCode);
if (evt.keyCode == 13 && node.nodeName == "INPUT" && node.type == "text") {
return false;
}
}
Perhaps there form element on your broken page(s) triggering the postback that is not a text node. Try removing the second part of the condition that prevents the submit, to see what happens:
if (evt.keyCode == 13) {
return false;
}

Categories

Resources