I am trying to add a keylistener to my input field but I can't make it work. My input type is text with id= "code". Here is what I tried:
document.querySelector('code').addEventListener('keypress', function (e) {
var key = e.which || e.keyCode;
window.alert(key);
});
and
document.getElementById('code').addEventListener("keydown", dealWithKeyboard, false);
function dealWithKeyboard(e) {
if (window.event) { // IE
keynum = e.keyCode;
} else if (e.which) { // Netscape/Firefox/Opera
keynum = e.which;
}
window.alert(keynum);
}
and
document.getElementById('code').onkeyup = function(e) {
if (window.event) { // IE
keynum = e.keyCode;
} else if (e.which) { // Netscape/Firefox/Opera
keynum = e.which;
}
window.alert(keynum);
}
But none seems to work
You aren't using the proper selector with document.querySelector(). An id value must be preceded by # as in document.querySelector('#code').
document.querySelector('#code').addEventListener('keypress', function (e) {
var key = e.which || e.keyCode;
console.log(key);
});
Working snippet:
document.querySelector('#code').addEventListener('keypress', function (e) {
var key = e.which || e.keyCode;
log(key);
});
// show output
function log(x) {
var div = document.createElement("div");
div.innerHTML = x;
document.body.appendChild(div);
}
Type some characters in the Input field here:
<input id="code">
Implemented properly, your document.getElementById('code') example should work.
If this still doesn't work, then check for two more things:
Make sure that you are executing this script AFTER the relevant parts of the DOM have been loaded. There are several ways to assure this, but the simplest is to just located the <script> tag after the HTML that it refers to.
Make sure that there are no script errors that are preventing your code from executing. You can check the debug console to check for errors.
Related
I have a problem with javascript keys, Chrome (only testing on chrome right now) does not recognise up and down arrows on text input, as it has this default behaviour in which it changes the caret position.
My code is as follows:
if (!e) e = window.event;
var keyCode = e.keyCode || e.which;
if (keyCode == '13'){ //enter key
//some code that works
return false;
}else if(keyCode=='38'){ //up key
//some other code that doesn't work
return false;
}else if(keyCode=='40'){ //down key
//some other code that doesn't work
return false;
}
If anyone has a solution I will greatly appreciate it.
Thank you!
Hard to see where the code is from (an keypress listener I guess).
As you can see below and this fiddle (and as Teemu also pointed out), keypress won't get called on arrow keys.
On another note, use event.preventDefault() to prevent the default behaviour of the browser, in your case the placing of the caret, also your listener functions can except an event object as a parameter.
var listener = function (e) {
e = e || window.event;
alert(e.type);
var keyCode = e.keyCode || e.which;
if(keyCode=='38' || keyCode=='40'){ //arrow key
alert("arrow!");
e.preventDefault();
return false;
}
}
var elem = document.getElementById('input');
elem.addEventListener('keydown', listener, false);
I have the following code which checks for "enter" key as well as prevent the use of > and < sign in the textbox.
<script type="text/javascript" language="javascript">
function checkKeycode(e) {
var keycode;
if (window.event) // IE
keycode = e.keyCode;
else if (e.which) // Netscape/Firefox/Opera
keycode = e.which;
if (keycode == 13) {
//Get the button the user wants to have clicked
var btn = document.getElementById(btnSearch);
if (btn != null) { //If we find the button click it
btn.click();
event.keyCode = 0
}
//Removed when above code was added 12-09-13
//CallSearch();
}
}
function CallSearch() {
var objsearchText = window.document.getElementById('txtSearchText');
var searchText;
if ((objsearchText!=null))
{
searchText = objsearchText.value;
searchText = searchText.replace(/>/gi, " >");
searchText = searchText.replace(/</gi, "< ");
objsearchText.value = searchText;
}
//This cookie is used for the backbutton to work in search on postback
//This cookie must be cleared to prevent old search results from displayed
document.cookie='postbackcookie=';
document.location.href="search_results.aspx?searchtext=";
}
</script>
How can I shorten the code to be more effecient and use the onBlur function and to use RegExp instead of replace? Or is replace a faster method than RegExp?
You are saying that you want to prevent < and > chars. Here is an easier way, just ignore these chars when the keydown event occurs on them.
Also I suggest to use jQuery - if you can.
http://api.jquery.com/event.which/
var ignoredChars = [188, 190]; // <, >
$('#myTextField').keydown(function(e) {
if(ignoredChars.indexOf(e.which) > -1) {
e.preventDefault();
e.stopPropagation();
return false;
}
})
.keyup(function(e) {
if(e.which === 13) {
$('#searchButton').click();
}
});
Just add this event handler to your textbox and remove the regexp replacements.
If you don't want characters to be input by user, surpress them as early as possible. This way you won't get in trouble fiddling them out of a big string later.
I write this Javascript code but it doesn't disable 2 windows keys (I mean logo key and menu key), though:
document.onkeydown = function(e) {
document.title = e.keyCode;
if (e.keyCode == 91 || e.keyCode == 93) {
window.event.keyCode = 0;
window.event.returnValue = false;
return false;
}
};
the 2 window.xxx statements are actually not necessary but I add them in to buy an insurance (Just doubt that e doesn't totally equal to window.event).
So I'd like to ask this question: " Is there a feasible way, directly or indirectly, to do this job in Javascript? "
Your code looks right, try to find out real keycodes with this simple script:
document.onkeydown = checkKeycode
function checkKeycode(e) {
var keycode;
if (window.event) keycode = window.event.keyCode;
else if (e) keycode = e.which;
alert("keycode: " + keycode);
}
And to disabel certain keys you modify function (example for 'Enter'):
document.onkeydown = checkKeycode
function checkKeycode(e) {
var event = e || window.event;
var keycode = event.which || event.keyCode;
if (keycode == 13) {
// return key was pressed
}
}
JavaScript cannot stop the effect of the Windows logo key, which (when released) is supposed to bring up the Window's start menu. In combination with other keys, it has other system wide effects (like with M = minimise all windows). This is something that happens outside of the browser context, and thus cannot and should not be blocked by the code running in your browser.
The Windows menu key can be somewhat disabled, as described in this answer:
$(function(){
var lastKey=0;
$(window).on("keydown", document, function(event){
lastKey = event.keyCode;
});
$(window).on("contextmenu", document, function(event){
if (lastKey === 93){
lastKey=0;
event.preventDefault();
event.stopPropagation();
return false;
}
});
});
<script>
function MoveNext(e, obj) {
if (!e) var e = window.event;
if (e.keyCode) code = e.keyCode;
else if (e.which) code = e.which;
if (code == 13) {
document.getElementById(obj).focus();
return false;
}
</script>
the above code is working in IE but not in mozilla why
change
if (e.keyCode) code = e.keyCode;
else if (e.which) code = e.which;
to
code = (e.keyCode)? e.keyCode: e.charCode;
and make sure your are passing your event to moveNext when you are calling it because firefox recognise event only if you sent it explicitly from the function.
also if your object that your are doing keydown is a div add to it a tabindex of 0 so it can retrieve focus .
<div id="mydiv" tabindex="0"></div>
Exactly what the best code is for the return key depends upon which keyboard event you are listening to (keydown, keyup, keypress). For keypress, you can do it like this:
function MoveNext(e, obj) {
e = e || window.event;
var code = e.which || e.keyCode;
if (code == 13) {
document.getElementById(obj).focus();
}
}
Note: I've remove your local variable e so it doesn't get confused with the argument e and I've defined code as a local variable which you had as an implicit global variable (never a good thing).
More on cross browser key handling described here: keycode and charcode.
here's what i got so far, i get "undefined" in the div instead of the actual letter pressed.
<script language="JavaScript">
document.onkeydown = checkKeycode;
function checkKeycode(e)
{
var keycode;
if (window.event)
{
keycode = window.event.keyCode;
}
else if (e) keycode = e.which;
var character = String.fromCharCode(keycode);
var letterDiv = document.getElementById("letter1");
letterDiv.innerHTML =character.innerHTML;
</script>
Here's JSFiddle Demo:
Set the letterDiv's innerHtml to that of var character not character.innerHTML. var character is a string not an Element.
document.onkeydown = checkKeycode;
function checkKeycode(e) {
var keycode;
if (window.event) {
keycode = window.event.keyCode;
}
else if (e) keycode = e.which;
var character = String.fromCharCode(keycode);
var letterDiv = document.getElementById("letter1");
letterDiv.innerHTML = character;
}
Remove innerHTML from character like so:
letterDiv.innerHTML = character;
Also, in your example, it appears that you are missing the end bracket } for your function. I suspect this problem does not exist in your actual project.