Setup asp.net default enter press client side - javascript

Working with asp.net, and I am trying to find a way to change default ENTER key press target on client side. Based on something like the currently focused div or input.
The target would be asp.net button controls with postback event.
Looking for solution for both IE and Firefox.
I am also using WebForm_FireDefaultButton(event, controlId) trying to set the default button but it doesn't work for Firefox; work fine for IE though.

Look at the Default Button property of an ASP.NET Panel Control

It's too difficult to answer this question without knowing the context. Generally speaking you must prepare javascript with required actions and then add something like
onkeydown = "if (event.keyCode == 13) submitForm(); if (event.keyCode == 27) cancelLogin();"
on client side or something similar on server side to action producing controls. The above example refers to MVC. For WebForms you can use __doPostBack instead of my submitForm() function (link text). Usually I used such scenario with inputs (TextBox controls for WebForms).

here is the cause and solution i just found
Asp.Net Form DefaultButton Error in Firefox
basically, on whatever event you prefer, call the following "FireDefaultButton" function to set the default fire button. The out of box function "WebForm_FireDefaultButton" does not compatible with Firefox (see the link for detail)
function FireDefaultButton(event, target)
{
// srcElement is for IE
var element = event.target || event.srcElement;
if (13 == event.keyCode && !(element && "textarea" == element.tagName.toLowerCase()))
{
var defaultButton;
defaultButton = document.getElementById(target);
if (defaultButton && "undefined" != typeof defaultButton.click)
{
defaultButton.click();
event.cancelBubble = true;
if (event.stopPropagation)
event.stopPropagation();
return false;
}
}
return true;
}

Related

How to disable key bindings in X3DOM

I am using X3DOM for a simple game, but I can't use keyboard keys the way I want to, because X3DOM reacts to them.
Example:
window.addEventListener('keydown', event => this.onKeyDown(event));
I want to have my own key event for if keyCode == 68. That works, but X3DOM reacts to it too, by changing the navigation mode and displaying an overlay.
How can I disable this?
disclaimer: I've never used x3dom, I was just poking around in the source code
there appears to be some code which disables keypress handling
this.disableKeys = x3dElem.getAttribute("keysEnabled");
this.disableKeys = this.disableKeys ? (this.disableKeys.toLowerCase() == "true") : false;
which is later read when setting up the keypress event handler:
this.onKeyPress = function (evt) {
if (!this.parent.disableKeys) {
evt.preventDefault();
this.parent.doc.onKeyPress(evt.charCode);
}
this.parent.doc.needRender = true;
}
So it appears setting keysEnabled=... attribute can turn this off. The oddity appears to be that their logic is backwards (?) for the condition:
x3dElem.getAttribute("keysEnabled") must be truthy (that is, it must have an attribute)
if that is falsey, this.disableKeys is always false
otherwise it is equal to that attribute's value lower-cased being equal to 'true'
So to disable keypress events, use <... keysEnabled="true" ...>
I made a github issue about the backwards logic, perhaps in the future it will be keysDisabled="true" instead
update:
in the latest version the attribute has been renamed to disableKeys so use <... disableKeys="true" ...>
You can use event.preventDefault to prevent X3DOM from reacting to that key:
window.addEventListener('keydown', event => {
if ((event.which === 68) || (event.keyCode === 68)){
event.preventDefault();
//
// ...
//
}
});

keypress event not generated in chrome but works in ie and ff

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

Submit a form with mouse middleclick button

I'm working on a system and I want to make the system easier to use.
I have few forms on a page and huge tables in each. I'm not good at JS so any advice would be appreciated.
Use a click event listener:
document.body.addEventListener('click', function(e){
if (e.button == 1){
document.formname.submit();
}
});
EDIT:
As per the new jQuery tag, it's slightly faster:
$('body').click(function(e){
if((!$.browser.msie && e.button == 1) || ($.browser.msie && e.button == 4)){
// IE exception thanks to #Elias Van Ootegem
$('form.myForm').submit();
}
});
Triggering onclick event using middle click
THE Above link will help.
$("#foo").live('click', function(e) {
if( e.which == 2 ) {
e.preventDefault();
alert("middle button");
}
});
The first line of jQuery allows it to work on the current line page,
'click' its telling it what event it has to listen for, and when the event is called it calls the function defined with the parameter e,
As it is the middle click you are looking for do a if statement to see what has been pressed, in your case you want which to equal 2.
Now as there may be some default actions set for this key, do e.preventDefault() so you able able to use your own code.
Al tough i would recommend using the enter key to submit a form as this is the everyday way of doing it.
I would recommend reading this aswell: http://unixpapa.com/js/mouse.html

Submit buttons and Enter key issues

I'm trying to prevent form submit if users has focus on any submit button or input type text (as in a filtering datagrid).
I'm considering 2 options
replace submit button with some kind of <p onclick='submitform&parameters'>Add</p>
block the enter key on buttons and some preferred input fields
Is there a better way to do this?
If you add an onKeyPress event to the element in question, you can prevent the default action (form submission) by returning false from the function:
<input id="txt" type="text" onKeyPress="var key = event.keyCode || event.which; if (key == 13) return false;"></input>
Note that the which property of the keyboard event is deprecated, but you'll still want to check for it to support older user agents and/or Internet Exploder (reference).
If you don't want to use inline javascript (which is not recommended), you can instead attach an event. Also, it may be better to use the preventDefault (docs) method of the event object, as well as the stopPropagation method (docs) - the necessity for these methods this is highly dependent on what other events you have attached to the form or the elements:
var preventFormSubmit = function (event) {
var key = event.keyCode || event.which;
if (key != 13)
return;
if (event.stopPropagation) event.stopPropagation();
else event.cancelBubble = true; // deprecated, for older IE
if (event.preventDefault) event.preventDefault();
else event.returnValue = false; // deprecated, for older IE
return false;
};
var target = document.getElementById('txt');
if (typeof target.addEventListener == 'function')
target.addEventListener('keypress', preventFormSubmit, false);
else if (typeof target.attachEvent == 'function')
target.attachEvent('onkeypress', preventFormSubmit);
There are other approaches to use, such as attaching a more complex onSumit handler to the form itself - this may be more appropriate if you're going to be doing further manipulation of the form or data before submitting (or using AJAX to submit the form data).
Solution
input id="txt" type="text" onKeyPress="if (event.which == 13) return false;"></input>
Link
http://stackoverflow.com/questions/1567644/submit-form-problem-enter-key
Question closed

Javascript: How can I block the backspace character?

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

Categories