My textbox is declared thus:
<asp:TextBox ID="txtShowManyItemTag" CssClass="price" onkeydown="return txtShowManyItemTagKeyUp(this);" TabIndex= "997" runat="server" Text="" Width="50px" />
The javascript function called is:
function txtShowManyItemTagKeyUp(txt) {
if (window.event.keyCode == 13 && txt.value != '') {
var nextRow = $(txt).closest('tr').next();
if (nextRow.length > 0) {
$(txt).closest('tr').next().find(".price").select();
}
else {
$("#<%=btnOkMany.ClientID %>").select();
}
return false;
}
}
In Chrome and IE, the window.event.keyCode == 13 correctly detects the Enter key being pressed, but I have been unable to find the equivalent for Firefox. Note that I am not passing an event, I'm passing the control that's triggering the event, and I can find no way to get the key code from that object. I'm going through stack overflow, but have not yet found something that matches this situation.
Thanks!
Instead of the onkeydown attribute, use
$("#txtShowManyItemTag").on('keydown', txtShowManyItemTagKeyUp);
And declare the function as
function txtShowManyItemTagKeyUp(e) { ... }
Inside it, you can now use e to refer to the event, and this to refer to the <input>.
Related
The snippet below shows the way I've coded an onKeyPress function to call a function when the Enter key is pressed. Will this handle all (or at least most) browsers?
function saveMarginKeyPress(thisArg, theEvent) {
// If property is present, call the saveButton onClick function and then exit
if ((theEvent.keyCode) && (theEvent.keycode == 13)) { saveMarginClicked(); return; }
if ((theEvent.charCode) && (theEvent.charCode == 13)) { saveMarginClicked(); return; }
if ((theEvent.which) && (theEvent.which == 13)) { saveMarginClicked(); return; }
}
function saveMarginClicked() {
alert("You pressed the Enter key");
}
<input id="marginTopText" onkeypress="saveMarginKeyPress(this, event)" name="marginTop" type="text" style="width: 28px" />
You might find my long names a bit overdone, I simply prefer to fully identify functions and fields with appropriate names.
Use the keydown or keyup event, and check the keyCode property. IE 5-7 did not trigger the keypress event for the enter key.
function saveMarginKeyPress(thisArg, theEvent) {
// If property is present, call the saveButton onClick function and then exit
if (theEvent.keyCode == 13) {
saveMarginClicked();
}
}
function saveMarginClicked() {
alert("You pressed the Enter key");
}
<input id="marginTopText" onkeydown="saveMarginKeyPress(this, event)" name="marginTop" type="text" style="width: 28px" />
The above is sufficient for all browsers today, and mostly likely for at least the next several years. However, you should be aware that there's finally a standard for keyboard events. Unfortunately, it's only implemented in IE and FireFox so far, but not yet in Chrome, Safari, and Opera. It would be a good habit to plan for the future by checking the key property first, before falling back to the legacy keyCode property:
function saveMarginKeyPress(thisArg, theEvent) {
// If property is present, call the saveButton onClick function and then exit
if (theEvent.key == "Enter" || theEvent.keyCode == 13) {
saveMarginClicked();
}
}
function saveMarginClicked() {
alert("You pressed the Enter key");
}
<input id="marginTopText" onkeydown="saveMarginKeyPress(this, event)" name="marginTop" type="text" style="width: 28px" />
Your theEvent may not be treated well in some browsers, so try something like that
onkeydown="var Key = (event) ? event.keyCode : e.which; if(Key==13)...
I am using dojo to disable other keypress events on dojo.form.numberTextBox.
I am doing in this way:
<input style="width: 100px" data-dojo-type="dijit.form.NumberTextBox"
name="test" id="test" maxlength="3">
And using the script:
require(["dojo/keys", "dojo/on"],
dojo.connect(dijit.byId("remainderDays"), "onKeyPress", function (evt) {
var charOrCode = evt.charCode || evt.keyCode;
if (charOrCode == keys.NUMPAD_0) {
dojo.stopEvent(evt);
}
}));
Its not working.
Even the Javascript function to disable keypress events except numbers is not working.
But when I remove dojo type from input, it starts working.
Any idea or help would be appreciated.
Well, you placed the dojo.connect wrong and if I understood well, you're trying to block all keys except the numbers. If you want that, you should check for something like:
if (evt.charOrCode > '9' || evt.charOrCode < '0') {
...
}
The code itself looks like:
require(["dijit/form/NumberTextBox"]);
require(["dojo/ready", "dojo/parser", "dojo/on", "dojo/keys"], function(ready, parser, on, keys) {
ready(function() {
parser.parse();
on(dijit.byId("test"), "keypress", function(evt) {
if (evt.charOrCode > '9' || evt.charOrCode < '0') {
dojo.stopEvent(evt);
}
});
});
});
As you can see I removed the dojo.connect (because it's deprecated) and I used the "keypress" event. I also fixed your code (because your syntax was wrong).
A working JSFiddle can be found here.
You can add the following line instead of using key press event:
var btnClick = dijit.byId("test")._onKey = function(evt) {
key = evt.keyCode;
if (key == dojo.keys.ENTER) {
//what you want it to do
}
}
I'm trying to disable the backspace button on an order page in all cases except when a textarea or text input is an active element to prevent users from accidentally backing out of an order. I have it working fine in most browsers, but in IE (testing in IE9, both regular and compatibility mode) it still allows the user to hit the backspace and go to the previous page.
Here's the code:
$(document).keypress(function(e){
var activeNodeName=document.activeElement.nodeName;
var activeElType=document.activeElement.type;
if (e.keyCode==8 && activeNodeName != 'INPUT' && activeNodeName != 'TEXTAREA'){
return false;
} else {
if (e.keyCode==8 && activeNodeName=='INPUT' && activeElType != 'TEXT' && activeElType != 'text'){
return false;
}
}
});
Any advice on what I'm doing wrong here?
Thanks!
I think you're overcomplicating that. Rather than checking for an active element, find the event target instead. This should give you the information you need. It's also better to use keydown rather than keypress when there is no visible character. Finally, it's better to use e.preventDefault() for better granularity.
$(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();
}
}
});
NB I could have done this the other way round, rather than an empty if block and all the code going in the else block, but I think this is more readable.
Instead of keypress, try the keydown function, it will fire before the actual browser based hook. Also, putting in a preventDefault() function will assist in this. IE :
$(document).keydown(function(e){
e.preventDefault();
alert(e.keyCode);
});
Hope this helps.
The most Simple thing you can do is add the following one line in the very first script of you page at very first line
window.history.forward(1);
Most examples seem to be for the JQuery framework - Here an example for ExtJS
(I've been getting a lot of downvotes for this recently as the question now has JQuery tag on it, which it didn't previously. I can remove the answer if you like as isn't for JQuery but it's proven to help others not using that framework).
To use this add this code block to your code base, I recommend adding it inside the applications init function().
/**
* This disables the backspace key in all browsers by listening for it on the keydown press and completely
* preventing any actions if it is not which the event fired from is one of the extjs nodes that it should affect
*/
Ext.EventManager.on(window, 'keydown', function(e, t) {
var nodeName = e.target.nodeName.toLowerCase();
if (e.getKey() == e.BACKSPACE) {
if ((nodeName === 'input' && e.target.type === 'text') ||
nodeName === 'textarea') {
// do nothing
} else {
e.preventDefault();
}
}
});
Use e.which instead of e.keyCode; jQuery normalizes this value across browsers.
http://api.jquery.com/keydown/
To determine which key was pressed,
examine the event object that is
passed to the handler function. While
browsers use differing properties to
store this information, jQuery
normalizes the .which property so you
can reliably use it to retrieve the
key code.
Then, use e.preventDefault(); to prevent the default behaviour of moving to the previous page.
<html>
<head>
<script type="text/javascript">
function stopKey(evt) {
var evt = (evt) ? evt : ((event) ? event : null);
var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
if ((evt.keyCode == 8) && (node.type!="text")) {return false;}
}
document.onkeypress = stopKey;
</script>
</head>
<body onkeydown="return stopKey()">
<form>
<input type="TEXTAREA" name="var1" >
<input type="TEXT" name="var2" >
</form>
</body>
</html
I had to add the onDownKey attribute to the body in order to get editing keys to go to the functions.
$(document).keydown(function(e) {
var elid = $(document.activeElement).is('input');
if (e.keyCode === 8 && !elid) {
return false;
}
});
Hope this might help you
Seems like the "backspace" will also act as "navigation back" if you have selected radio buttons, check-boxes and body of document as well. Really annoying for forms - especially when using post. All the form could be lost with one slip of the "backspace" key -_- ...
Honestly... who's idea was it to allow the "backspace as a navigational "back" button!!! really bad idea in my opinion.
I disable the "backspace" default on anything that is not a text area or text field - like this:
$(document).keydown(function(e){
console.log(e.keyCode+"\n");
var typeName = e.target.type;//typeName should end up being things like 'text', 'textarea', 'radio', 'undefined' etc.
console.log(typeName+"\n");
// Prevent Backspace as navigation backbutton
if(e.keyCode == 8 && typeName != "text" && typeName != "textarea"){
console.log("Prevent Backbutton as Navigation Back"+typeName+"\n");
e.preventDefault();
}
//
})
Not sure where else one would want the normal behavior of a back-button other than in these two areas.
document.onkeydown = KeyPress;
function KeyPress(e) {
if (!e.metaKey){
e.preventDefault();
}
}
<body id="body" runat="server" onkeydown="return showKeyCode(event)">
Now whenever I hit a key, IE8 (or in comp mode) throws an exception directing to a problem
in line x, which happens to be my body tag. How can I prevent that ?
The JS code to my knowledge should be with IE comp. (works in Chrome)
Moreover the code doesn't work in IE and Firefox (it doesn't block F5 and Enter)
--> Object expected
var version = navigator.appVersion;
function showKeyCode(e) {
var keycode = (window.event) ? event.keyCode : e.keyCode;
if ((version.indexOf('MSIE') != -1)) {
if (keycode == 13) {
event.keyCode = 0;
event.returnValue = false;
return false;
}
}
else {
if (keycode == 13) {
return false;
}
}
}
Another problem I'm facing is with this simple JS in IE & FF (works in Chrome):
Nothing happens & --> Object expected
<a onclick="ClearTextboxes();" title="Close" id="close" runat="server">Close</a>
....in script tags:
function ClearTextboxes() {
document.getElementById('<%= txtbox_name.ClientID %>').value = '';
document.getElementById('<%= txtbox_email.ClientID %>').value = '';
document.getElementById('<%= txtbox_content.ClientID %>').value = '';
document.getElementById('<%= ResultMail.ClientID %>').style.display = 'none';
}
You have a lot of unnecessary code in your showKeyCode function. The following will do just as well; you're already guaranteed that e will refer to the key event object becuase of the way you're passing in event in the body's onkeydown attribute, and there's no need for any browser sniffing at all. return false is the correct way to prevent the browser's default action when using a DOM0 key handler, so no need for e.returnValue.
You'll have problems blocking F5 and unless you have a seriously good reason you shouldn't do it anyway, since the user is used to it performing a page refresh. If you change the function to the following then there's no reason why it shouldn't prevent the Enter key's default action:
function showKeyCode(e) {
if (e.keyCode == 13) {
return false;
}
}
I am using asp:button to create a keyboard with A-Z and 0-9 for touch screen using Java script. This keyboard is linked with one textbox. If we click one button corresponding text will be displayed on the textbox. Its working fine. I have included the autocomplete feature to this textbox using jquery JQuery Autocomplete.
Problem:
The autocomplete is not working if i my user define keyboard. How to modify my key buttons as keyboard keys[Set event keycode]? Is it possible? Is there any other way to achieve this?
Code:
<asp:TextBox ID="txtSearch" runat="server"></asp:TextBox>
<asp:Button ID="zero" runat="server" Text="0" CssClass="myclass" OnClientClick="return typeLetter(this);" TabIndex="20"/>
function typeLetter(currentbutton) {
if (previousActiveElement != null) {
if (previousActiveElement == 'antSearchText'){
var position = document.getElementById('position').value;
if (position == '') {
alert('chk position');
} else {
var existingString = document.getElementById(previousActiveElement).value;
var beforeString = existingString.substring(0, position);
var afterString = existingString.substring(position, existingString.length);
document.getElementById(previousActiveElement).value = beforeString + currentbutton.value + afterString;
setCaretPosition(document.getElementById(previousActiveElement), parseInt(position) + 1);
setCaretPosition(document.getElementById(previousActiveElement), parseInt(position) + 1);
}
}
}
return false;
}
Edit:
In autocomplete plugin the following is getting the key event, How to pass same key event by using my keys?
$input.bind(($.browser.opera ? "keypress" : "keydown") + ".autocomplete", function(event) {
}
Try triggering the jQuery keydown/keyup event manually. I cannot recall for the life of me which one autocomplete triggers on, but here's the gist:
// your documment.getElementById(...)
jQuery('#'+previousActiveElement).keyup();
// your setCaretPosition
Try the different key events and one should cause the autocomplete to kick in.
Hope that helps!
Thanks,
Joe
Problem get solved by using the following code.
Code:
var q = document.getElementById('txtbox');
var evObj = document.createEventObject();
evObj.keyCode = 84; // [T] key
q.fireEvent('onkeydown', evObj);
Geetha.