Digit-only input keycode verifier also accepting forward-slash - javascript

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

Related

Javascript functions are not working in Firefox new version

I have the following below function which disables to enter numbers or special characters in the text box. This function are working fine in IE and Chrome, but in the firefox these are not working and am able to enter the numbers and characters. Can anyone please suggest how this can be resolved in firefox? My FF version is 57.0.4
$("#firstName").keypress(function(event) {
var character = String.fromCharCode(event.keyCode);
return isValid(character);
});
function isValid(str) {
return !/[~`!##$%\^&*()+=\-\[\]\\';,/{}|\\":<>\?]/g.test(str);
}
$( document ).ready(function() {
$( "#firstName" ).keypress(function(e) {
var key = e.keyCode;
if (key >= 48 && key <= 57) {
e.preventDefault();
}
});
keyCode is deprecated. jQuery normalizes this property for cross browser usage in the event.which property.
$("#firstName").keypress(function(event) {
var character = String.fromCharCode(event.which);
return isValid(character);
});
function isValid(str) {
return !/[~`!##$%\^&*()+=\-\[\]\\';,/{}|\\":<>\?]/g.test(str);
}
$("#firstName").keypress(function(e) {
var key = e.which;
if (key >= 48 && key <= 57) {
e.preventDefault();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id=firstName />
To disables to enter numbers or special characters you can use
/[~`!##$%\^&*+=\-\[\]\\';,_./{}\(\)\|\\":<>\d+$?]/g
You can try this regex Here And instead of using keypress() you can use .on('input') .. The next code works for me in chrome , firefox and IE
$("#firstName").on( 'input' ,function(event) {
var ThisVal = $(this).val();
if(isValid(ThisVal) == false){
$(this).val(ThisVal.substr(0, ThisVal.length - 1));
}
});
function isValid(str) {
return !/[~`!##$%\^&*+=\-\[\]\\';,_./{}\(\)\|\\":<>\d+$?]/g.test(str);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id=firstName />
Note: I don't care here to use e.which or e.keyCode because no need to in this case .. Also this regex will disable _ and . and - if you need any of those you can remove it

JavaScript: Using up and down arrows on input text

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

How to replace code to use RegExp

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.

How to disable Windows keys (logo key and menu key) using Javascript

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

need help to display letter pressed in a div with javascript

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.

Categories

Resources