Prevent backspace from navigating back in AngularJS - javascript

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.

Related

Different back space handling in different controllers

This controller is for page1.html
test1.controller('test1Controller', function($scope,$document) {
$document.on('keydown', function(e){
if(e.which === 8 && e.target.nodeName !== "INPUT" && e.target.nodeName !== "SELECT"){
confirm("you are In Home page");
}
});
}
This controller is for page2.html
test2.controller('test2Controller', function($scope,$document) {
$document.on('keydown', function(e){
if(e.which === 8 && e.target.nodeName !== "INPUT" && e.target.nodeName !== "SELECT"){
//HERE CODE LOGIC SHOULD COME TO PREVIOUS PAGE
}
});
}
I entered data in page1 and moved to page2.html and click on backspace of keyboard,
Although i am on second page,function in test1Controller is getting invoked.
What is wrong with the above logic..
With the current above code,both the functions in two different controllers are being invoked.
Unbind all keydown events before you bind the new one in your controllers by doing
For controller one
test1.controller('test1Controller', function($scope,$document) {
$document.off('keydown')
$document.on('keydown', function(e){
if(e.which === 8 && e.target.nodeName !== "INPUT" && e.target.nodeName !== "SELECT"){
confirm("you are In Home page");
}
});
}
For controller two
test2.controller('test2Controller', function($scope,$document) {
$document.off('keydown')
$document.on('keydown', function(e){
if(e.which === 8 && e.target.nodeName !== "INPUT" && e.target.nodeName !== "SELECT"){
//HERE CODE LOGIC SHOULD COME TO PREVIOUS PAGE
}
});
}

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

Insert a CR/LF into a textarea

I've got the following code:
document.onkeydown=function(e) {
if (e.which == 13 && isCtrl) {
log('Ctrl CR');
} else if (e.which == 17) {
isCtrl = true;
};
I need to insert a Carriage Return/Line feed where the cursor is located in the input textarea.
Now that I think about it, I should probably be using a textarea selector instead of document.onkeydown, but $('textarea').onkeydown doesn't work.
$('textarea').keydown(function (e){
var $this = $(this);
if (e.which === 13 && e.ctrlKey) {
$this.val($this.val() + '\r\n'); // untested code (to add CRLF)
}
});
Reference
.keydown
Event object

disable enter key on page, but NOT in textarea

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);
});

Categories

Resources