Handle key using javascript onkeydown - javascript

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>

Related

Detect Enter keypress in html input without jquery

I just want to detect the enter input keypress on my android device. I found out that using jquery, we can do like below:
$('#inputText').keypress(function(event) {
var keycode = event.keyCode || event.which;
if(keycode == '13') {
alert('You pressed a "enter" key in somewhere');
}
});
But I don't want to use jquery. I want to use the traditional way like using
document.getElementById('inputText')
But I don't know how to add in the keypress event function. Do you guys have any idea?
Almost the same as in jQuery. Use eventListener and pass an argument e to the function to catch the event and it's keyCode.
var elem = document.getElementById('inputText');
elem.addEventListener('keypress', function(e){
if (e.keyCode == 13) {
console.log('You pressed a "enter" key in somewhere');
}
});
<input id='inputText'>
document.getElementById("id").onKeyDown = function(event) {
if (event.keycode === 13) {
alert("return pressed");
}
};
Use event.key instead of event.keyCode!
const node = document.getElementById('inputText');
node.addEventListener('keydown', function onEvent(event) {
if (event.key === "Enter") {
// Do something
}
});
Mozilla Docs
Supported Browsers
You can use
document.getElementById('txtBox').onkeypress = function(e) {
if (!e) e = window.event;
var keyCode = e.keyCode || e.which;
if (keyCode == '13') {
alert("Enter Pressed");
}
}
<input id="txtBox" type="text" />
You can use addEventListener
document.getElementById('inputText').addEventListener("keypress", function() {});
Do this :
<form onsubmit="Search();" action="javascript:void(0);">
<input type="text" id="searchCriteria" placeholder="Search Criteria"/>
<input type="button" onclick="Search();" value="Search" id="searchBtn"/>

JavaScript keyListener

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.

backspace not working during validation in firefox

I have written the below code so that users only enter numbers. It works fine in all the browsers excepts FireFox
In FireFox after entering a number if the users clicks backspace it is not working properly. Below is the code.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript">
function getKeyCodeFromEvent(e) {
if (typeof e == "object" && typeof e.which == "number") {
return e.which;
}
return window.event.keyCode;
}
function checkEntry(e) {
var keyCode = this.getKeyCodeFromEvent(e);
var regularExpression = /^[0-9.]+$/;
return regularExpression.test(String.fromCharCode(keyCode));
}
</script>
</head>
<body>
<input type="text" onkeypress="return checkEntry(event);" />
</body>
</html>
When someone presses the backspace key, you get the value 8 from getKeyCodeFromEvent. Running it in String.fromCharCode(8); then returns the following unicode value: ``. This does not match your regex, so it fails.
You could solve this by checking that the backspace, delete, tab, left and right keys are allowed, before turning them into String values. You will need to use the keydown event though, because keypress does not return values for certain keys, such as left or right.
Be careful when restricting user movement like this though, as it might easily make people angry, when the site doesn't work as they expect it to.
<script>
function getKeyCodeFromEvent(e) {
if (typeof e == "object" && typeof e.which == "number") {
return e.which;
}
return window.event.keyCode;
}
function checkEntry(e) {
var keyCode = getKeyCodeFromEvent(e);
var regularExpression = /^[0-9.]+$/;
// If the key is backspace, tab, left, right or delete
if([8,9,37,39,46].indexOf(keyCode) !== -1 || e.ctrlKey || e.metaKey) {
return true;
}
if(!regularExpression.test(String.fromCharCode(keyCode))) {
e.preventDefault();
e.returnValue = false;
return false;
}
}
// I took the liberty of moving your event from the HTML into JavaScript, where it belongs
document.addEventListener("DOMContentLoaded", function() {
document.getElementById('numberinput').addEventListener("keydown", checkEntry, false);
}, false);
</script>
<input type="text" id="numberinput" />
http://jsfiddle.net/8hzwLjfz/6/

Determining which key was pressed

This way works but it strikes me as working too hard.
Question: How do you determine which key has been pressed?
;(function() {
var Variables = {}
Variables.slash = false
$('[name=myName]').keypress(keypress)
function keypress(myEvent) {
if (myEvent.which === 47) {
Variables.slash = true
}
}
$('[name=myName]').keyup(keyup)
function keyup(myEvent) {
if (Variables.slash) {
Variables.slash = false
}
}
})()
It can be simplified, by following steps:
You need to find out the ASCII code of the key pressed (https://api.jquery.com/event.which/)
Now just use a ASCII reference table and find out which char was pressed.
The myEvent variable will contain the ASCII code of the key that have been pressed.
The ASCII code of slash is 47. (See here)
From a previous question:
"Clear" JavaScript:
<script type="text/javascript">
function myKeyPress(e){
var keynum;
if(window.event){ // IE
keynum = e.keyCode;
}
else if(e.which){ // Netscape/Firefox/Opera
keynum = e.which;
}
alert(String.fromCharCode(keynum));
}
</script>
<form>
<input type="text" onkeypress="return myKeyPress(event)" />
</form>
JQuery:
$(document).keypress(function(event){
alert(String.fromCharCode(event.which));
})

fire a button with pressing ENTER after coming with TAB to it

there is a button in my code. Apart from using mouse and clicking it, I'd like to fire (pressing ENTER) it after selecting it with TAB.
<div id="CloseButton" tabindex="0" onkeypress="return submitOnEnter(blah,event)">Close</div>
if it helps:
function submitOnEnter(blah,e) {
var keycode;
if (window.event) keycode = window.event.keyCode;
else if (e) keycode = e.which;
else return true;
if (keycode == 13) {
//at this point I need to fire a button w/o using its id
return false;
} else {
return true;
}
}
If someone knows how to do it?
Is it possible to make 'blah' refer to <div>, such that I could do:
$(blah).click();
this could work:
jQuery(':focus').click()
here is my solution:
part of HTML, close button is a div element and is a part of a modal window:
...
<div class="closeButton">
<span id="closeSpan" tabindex="0">Close</span>
</div>
...
JS, within the ModalWindow class:
$(modWin).find("#closeButton").one("click",
this.close).keypress(this.doNothing);
this.close = function () {
$("#modalWindow").css("display","none").fadeOut(200).html("");
$("#modalWindow #closeButton").hide();
$(window.self.document.body).find("#modalWindow").remove();
}
this.doNothing = function (e) {
var keycode;
if (window.event) keycode = window.event.keyCode;
else if (e) keycode = e.which;
else return true;
if (keycode == 13) {
innerthis.close();
return false;
} else {
return true;
}
}
PS: innerthis is defined within the ModalWindow class as:
var innerthis = this;

Categories

Resources