This question already has an answer here:
Closed 11 years ago.
Possible Duplicate:
javascript backspace by default problem…Going back a page.
The issue I am having is when you type a list of phone numbers into the list and then when you click one to edit it, if you backspace to delete the number, it will mess the entire list up by going back one page....i am fully aware that this is because the default back page is backspace and thats why its doing that but I really want it to not backpage when I use backspace to delete a number from the list.....
So what I am saying basically is how can I disable backspace to back page......
Here is a fiddle:
http://jsfiddle.net/bikbouche1/QVUHU/67/
you can override the Backspace button action using the following code snippet:
function suppressBackspace(evt) {
evt = evt || window.event;
var target = evt.target || evt.srcElement;
if (evt.keyCode == 8 && !/input|textarea/i.test(target.nodeName)) {
return false;
}
}
document.onkeydown = suppressBackspace;
document.onkeypress = suppressBackspace;
This should work in all browsers and it also filters out events that originated from an input or textarea element.
So if you want to use the backspace button for another action you can call the function there where it suppresses the default browser action.
to block backspace you can use this:
document.onkeydown = function(evt) {
evt = evt || window.event;
var keyCode = evt.keyCode;
if (keyCode == 8) { // backspace
return false;
}
};
Backspace only makes the page go back if you don't have focus in a form field. With your Jsfiddle, I didn't have your issue.
Related
Hi I am trying to trigger a click event when enter key is pressed but i'm not sure of a way to do it for ie6
Maybe this:
if (document.attachEvent) {
document.attachEvent("keypress", function(e) {
var keyCode = e.which || e.keyCode
if (keyCode === 13) document.getElementById("button1").click()
})
}
If you really need to do this on IE6, there you go (make sure this is run in IE<9 only):
var input = document.getElementById('some_input'), // Presumably an input element
element = document.getElementById('some_element'); // The element to click
input.attachEvent('onkeydown', function (e) {
if (e.keyCode != 13) {return;} // Quit, no ENTER pressed
element.click();
// Prevents the default action of the event
e.cancelBubble = true;
e.returnValue = false;
return;
});
keydown needs to be listened, since keypress doesn't detect ENTER, and keyup is not cancelable. If the element ENTER was pressed on, is input element, you've to prevent the default action to prevent a form being submitted. Some early IE versions submitted a form on the page even when the input was outside of the form. If the element you're going to hit ENTER is not an input element, or you don't have any forms on the page, the default action preventing is not needed.
I am trying to change the behaviour of selects in an html form.
I would like that when a user navigates the form using the keyboard, if they are selecting an element and presses tab, the element is selected and the focus switches to the next form input. Normally, you need to press enter to select the element and then you can use tab to switch to the next one. If enter isn't pressed, no option is selected.
To do this, I want to capture the TAB keypress and trigger an ENTER keypress followed by a TAB.
This is what I have for now:
$('form[class="ui form"]').on('keydown', 'div[class="ui fluid selection dropdown active visible"]', function (e) {
var keyCode = e.keyCode || e.which;
if (keyCode == 9) {
e.preventDefault();
var y = jQuery.Event('keydown', {which: 13});
$(this).trigger(y);
var x = jQuery.Event('keydown', {which: 9});
$(this).trigger(x);
}
});
Here is a demo: JSFiddle
The code 'works' up to e.preventDefault(), the tab keypress doesn't switch the focus to the next input. However, the enter and tab actions aren't triggered, so nothing happens. What should I do ?
Thank you in advance !
UPDATE 10/10: Found the problem! Triggering event x (tab keypress) makes the code enter an infinite loop. Therefore the whole approach is wrong. I'll soon post an answer.
When I try it passing whichas the event object, it does work jsfiddle.net/mendesjuan/sL7tnfm6/5
$('form[class="ui form"]').on('keydown', 'div[class="ui fluid selection dropdown active visible"]', function (e) {
var keyCode = e.keyCode || e.which;
if (keyCode == 9) {
e.preventDefault();
var y = jQuery.Event('keydown', {which: 13});
$(this).trigger(y);
}
});
The draft code in the question triggers an infinite loop. The key point in the problem is capturing the selected (active) element when the user presses TAB and switches the focus to the next element.
So, it is better to use a function called onblur:
$('form[class="ui form"]').on('blur', '.dropdown', function () {
var y = jQuery.Event('keydown', {which: 13});
$(this).trigger(y);
});
This question has been asked plenty of times before, but no answers I have found seem to solve my problem.
From a classic asp page I call a Javascript function
on each of my pages. The point is to fire a search button when a user enters search text and presses enter, rather than clicking on the button, or choosing from the Ajax provided selections.
This works fine in IE and FF, as has been the case for every other question asked along these lines.
Here is the Javascript. Can anybody tell me please how to have it work for Chrome as well as IE and FF ?
Edited following answer form Alexander O'Mara below:
Altered function call in body tag on page to use onkeyup instead of onkeypress - onkeyup="KeyPress(event)"
Altered JS function (also after heeding comments re duplication from others - thanks) as follows:
function KeyPress(e)
{
var ev = e || window.event;
var key = ev.keyCode;
if(window.event) // IE
{
key = e.keyCode;
if (key == 13)
{
window.event.keyCode = 0;
$('#btnSearch').click();
}
}
else if (key == 13)
{
btnSearch.click();
ev.preventDefault();
}
}
It seems to work sometimes and not others, and rarely on chrome currently. Is there a guaranteed way to have it work all the time ?
The main page of my site if you want to try it yourself is www.dvdorchard.com.au, your cursor will be sitting in the search box on arrival - enter a word > 3 chars and press enter, if you stay on the page it didn't work, if you move to the productfound.asp page it worked.
Thanks again.
You are looking for the keyup event (documentation). The keypress event is not consistent across browsers. See this question for information on the differences.
Update:
Since you are using jQuery, you can also remove the onkeyup="KeyPress(event)" attribute for you body, and replace your KeyPress function with the following (replacing the contents with your event handling code).
$(window).keyup(function(e){
/*YOUR CODE HERE*/
});
if(e.keyCode)
{
key= e.keyCode;
}
else
{
key = e.charCode;
}
Fire your event with onkeyup
read more
this should work in chrome. I don't know about other browsers
function code(e) {
e = e || window.event;
return(e.keyCode || e.which);
}
window.onload = function(){
document.onkeypress = function(e){
var key = code(e);
// do something with key
// done doing something with key
key=0
};
};
I'm using the below JavaScript function to prevent backspace from going back.
function preventBackspace(e) {
var evt = e || window.event;
if (evt) {
var keyCode = evt.charCode || evt.keyCode;
if (keyCode === 8) {
if (evt.preventDefault) {
evt.preventDefault();
} else {
evt.returnValue = false;
}
}
}
}
I have added onkeydown="preventBackspace();" to all the text boxes.
I have two radio buttons and two textboxes which when checked make the other textbox readonly. When hitting the backspace key it is not going to back page, but I am not able to delete from the editable text box. Please suggest. Thanks!
When the user is currently focused on a textbox, the backspace key does not cause the browser to go back. The backspace in a textbox is used to delete a character - and since you've added preventDefault(), you're stopping that behavior from happening.
If your goal is to prevent the user from accidentally leaving the form before they are finished, you can use window.onbeforeunload to display a warning message that allows the user to cancel navigation:
window.onbeforeunload = function() {
return "Are you sure you want to leave this page? Your current entries" +
" will be lost.";
};
I don't want my website's user to use backspace to go to the previous page,
but I still want to keep the use of backspace,
just like deleting wrong typing.
How can I do?
Thanks a lot.
As others have mentioned there are methods in which you can monitor for backspace key events and perform different actions.
I recommend against catching the backspace key for a couple of reasons:
1) It's simply irritating and irritated users are likely to not return to your page.
2) Backspace is not the only method of returning to the previous page. There are other key combinations that can accomplish the same thing, as well as the obvious "back button".
Don't do it - but if you must, use onbeforeunload() rather than trapping browser specific key strokes.
Solution: Place the following code toward the end of all your pages that contain forms:
<!-- Block the Backspace and Enter keys in forms, outside of input texts and textareas -->
<script type="text/javascript">
function blockBackspaceAndEnter(e) {
if (!e) { // IE reports window.event instead of the argument
e = window.event;
}
var keycode;
if (document.all) {
// IE
keycode = e.keyCode;
} else {
// Not IE
keycode = e.which;
}
// Enter is only allowed in textareas, and Backspace is only allowed in textarea and input text and password
if ((keycode == 8
&& e.srcElement.type != "text"
&& e.srcElement.type != "textarea"
&& e.srcElement.type != "password")
|| (keycode == 13 && e.srcElement.type != "textarea")) {
e.keyCode = 0;
if (document.all) {
// IE
event.returnValue = false;
} else {
// Non IE
Event.stop(e);
}
}
}
for (var i = 0; i < document.forms.length; i++) {
document.forms[i].onkeydown = blockBackspaceAndEnter;
}
</script>
I have the following comments about what other people answered here before:
Someone said:
"Please don't. Users like
backspace-to-go-back; going back is
one of the most vital browser features
and breaking it is intolerably rude."
My answer to him is:
Yes, usually people DO use the back-button to go back, BUT NOT on pages with FORMS. On the other hand it is really easy for people to accidentally click near or outside an input text or textarea, and then press the back button, so they will lose all their edits, as someone else also noticed:
"Users aren't in a textbox and hit the
backspace, completely losing all the
form information they've just entered.
Wouldn't normally be a problem, but
for us, we're filling out lots of text
on long state forms."
The same undesired behaviour can also be said about the Enter key to submit the form, which usually is only desirable (if ever) for small forms with a few fields, but not for forms with many fields and select boxes and input boxes and textareas, in which most of the time you DO NOT want that the form is submitted when you press Enter.
So this is why I suggest the code above, which applies to all <FORM> tags the function suggested by webster, but without the checks for ALT, which I don't think is useful, and without the checks for CTRL+N and CTRL+R and CTRL+F5, which we don't want to block, because when they are used they are NOT accidental.
Unfortunately, the code above does not work in Firefox when you have DIVs and TABLEs inside your FORM! That is because the keydown event seems to not be propagated to the containing form, and instead the default (UNDESIRED!) behaviour is applied for the Backspace and Enter keys.
I couldn't yet find a solution for this one...
You can use the "onbeforeunload" property on the body tag to prompt the user that he is leaving the page.
You can simply use the following code snippets to block the backspace when the cursor is in texarea, text and password controls.
function onKeyDown()
{
if((event.altKey) || ((event.keyCode == 8) &&
(event.srcElement.type != "text" &&
event.srcElement.type != "textarea" &&
event.srcElement.type != "password")) ||
((event.ctrlKey) && ((event.keyCode == 78) || (event.keyCode == 82)) ) || (event.keyCode == 116) ) {
event.keyCode = 0;
event.returnValue = false;}
}
Call this function from body tag onkeydown event
Filme Noi Cinema has the right answer, but the example code is a bit dated. I just needed this solution so I thought I would post the code I used.
//I use the standard DOM method for accessing the body tag, because the
//non-standard HTML DOM shortcuts are not stable. The correct behavior is
//dynamically attached to the entire body using the onkeypress event, which
//is the most stable event to target cross browser.
document.getElementsByTagName("body")[0].onkeypress = function (event) {
var a = event || window.event, //get event cross browser
b = a.target || a.srcElement; //get source cross browser
//the only thing that matters is the backspace key
if (a.keyCode === 8) {
//if you are a textarea or input type text or password then fail
if (b.nodeName === "textarea" || (b.nodeName === "input" && (b.getAttribute("type") === "text" || b.getAttribute("type") === "password"))) {
return true;
} else {
//backspace is disabled for everything else
return false;
}
}
};
This code needs to be executed before the user starts engaging the page. There are numerous ways to do this:
You can put the above code into any function that is already attached to the onload event.
You can wrap the above code that is bound to the page's onload event.
You can put the above code into a self executing function.
Examples:
//self executing function
(function () {
the solution code here
}());
//wrapper to onload event
document.getElementsByTagName("body")[0].onload = function () {
the solution code here
};
I am adding this code to Pretty Diff if you want to see an example in action.
You should be able to attach a onKeydown/Up/Press listener to your window. In this function, look at the keycode that was pressed, and at the event target. If the keycode is backspace, and the target is NOT an input box or a textarea, prevent the event.
I finally found one that works on all browsers.
It's by Hazem Saleh
His website address is:
http://www.technicaladvices.com/2012/07/16/preventing-backspace-from-navigating-back-in-all-the-browsers/
/*Starts here:*/
document.onkeydown = function (event) {
if (!event) { /* This will happen in IE */
event = window.event;
}
var keyCode = event.keyCode;
if (keyCode == 8 &&
((event.target || event.srcElement).tagName != "TEXTAREA") &&
((event.target || event.srcElement).tagName != "INPUT")) {
if (navigator.userAgent.toLowerCase().indexOf("msie") == -1) {
event.stopPropagation();
} else {
alert("prevented");
event.returnValue = false;
}
return false;
}
};
/*Ends Here*/