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.
Related
I wrote a piece of code which will only accept numeric value as key event. It should only accept 0-9 and backspace. But it also allows forward slash as input.
element.addEventListener('keypress',function(event){
var charcodeAcceptable=[47,48,49,50,51,52,53,54,55,56,57,8];
if (window.event) {
var charCode = window.event.keyCode;
}
else if (event) {
var charCode = event.which;
}
if(charcodeAcceptable.indexOf(charCode)==-1){
event.preventDefault();
}
});
The ASCII code for the forward slash / is 47, therefore your indexOf returns 0 and not -1.
After my orginal response quoted below, and based on the comment left by #t.niese I have created an updated pen.
http://codepen.io/ballerton/pen/PzOdxW
Essentialy, use event.key to get the value of the key press and then test against allowed values:
element.addEventListener('keypress',function(event){
var charcodeAcceptable=['1','2','3','4','5','6','7','8','9','0','Backspace'];
if (window.event) {
var charCode = window.event.key;
}
else if (event) {
var charCode = event.key;
}
if(charcodeAcceptable.indexOf(charCode)==-1){
event.preventDefault();
}
});
I have modified the code to use event.keyCode and it works as
expected.
http://codepen.io/ballerton/pen/vKWzRO
element.addEventListener('keypress',function(event){
var charcodeAcceptable=[47,48,49,50,51,52,53,54,55,56,57,8];
if (window.event) {
var charCode = window.event.keyCode;
}
else if (event) {
var charCode = event.keyCode;
}
if(charcodeAcceptable.indexOf(charCode)==-1){
event.preventDefault();
}
});
original pen by Chris Coyier
see comment by #t.niese
With regard to the test itself, is it important t test to see if it is
a window event?
If not could you not just use:
element.addEventListener('keypress',function(event){
var charcodeAcceptable=[47,48,49,50,51,52,53,54,55,56,57,8];
if(charcodeAcceptable.indexOf(event.keyCode)==-1){
event.preventDefault();
}
});
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.
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;
}
});
});
I have this code
function verifyKey(e)
{
var keycode;
if (window.event)
keycode = window.event.keyCode;
else if (e)
keycode = e.which;
regex=/[1-9]/;
if(regex.test(keycode))
return true;
else
void(0);
}
in the html I added an input and I add the onkeydown event onkeydown="verifyKey(event);"
I like to verify the key before it display on the text
If the key is a number or coma(,) or full stop(.)
then accept the key
else
refuse it
Thanks
Here in your code you are testing the regular expression defined with the keycode, so every chearactes on the keyboard will be allowed since the keycode of every key is numbers, so you will not get the result what you expect. Instead of using the regular expression try the below code
<html>
<head>
<script type="text/javascript">
function verifyKey(e)
{
var keycode;
if (window.event)
keycode = window.event.keyCode;
else if (e)
keycode = e.which;
if((keycode>=48 && keycode<=57))
{alert("if")
return true;
}
else if((keycode == 188)||(keycode == 190))
{alert("elseif");
return true;
}
else
{alert("else")
return false;
}
}
</script>
</head>
<body>
<input type="text" onkeypress="return verifyKey(event)" />
</body>
</html>