Why my condition is not satisfied? - javascript

I have a textbox and i want to allow users only enter 4 digits as i want to take time from the user, but i am facing the strange problem in condition.
Fiddle Demo
Javascript
function CheckLength(val, key) {
var keycode = (key.which) ? key.which : key.keyCode;
if(!(keycode == 8 || keycode == 46) && (keycode < 48 || keycode > 57))
return false;
if (val.length < 4)
console.log(val);
else
return false;
}
HTML Markup
<input type="text" id="timepick" onkeyup="return CheckLength(this.value,event);" />
Can anyone help me? why this is happening?
Thanks for your precious time.

You could listen for a "keydown" event instead of "keyup" Heres your Fiddle, (i only changed up to down). , or remove the last entered key by resetting the value in the "keyup" event.
document.getElementById("timepick").addEventListener("keyup", function (e) {
var keycode = (e.which) ? e.which : e.keyCode;
if (e.target.value.length <= 4) console.log(e.target.value)
if (!(keycode == 8 || keycode == 46) && (keycode < 48 || keycode > 57) || e.target.value.length > 3)
e.target.value = e.target.value.substr ( 0,4)
});
Like in this Fiddle
Or you could use 2 seperate events, one "keydown" to prevent the input, and a keyup to read the value
document.getElementById("timepick").addEventListener("keydown", function (e) {
var keycode = (e.which) ? e.which : e.keyCode;
if (!(keycode == 8 || keycode == 46) && ((keycode < 48 || keycode > 57) || e.target.value.length > 3) e.preventDefault()
});
document.getElementById("timepick").addEventListener("keyup", function (e) {
if (e.target.value.length == 4) console.log(e.target.value)
});
Like in this Fiddle
Update, regarding your comment
You could, of course use only a "keydown" event, and build the value you want on your own.
document.getElementById("timepick").addEventListener("keydown", function (e) {
var keycode = (e.which) ? e.which : e.keyCode;
if (!(keycode == 8 || keycode == 46) && ((keycode < 48 || keycode > 57) || e.target.value.length > 3)) e.preventDefault()
if (e.target.value.length == 3) console.log(e.target.value + String.fromCharCode(keycode))
});
Like in this Fiddle

Hope this helps you. It prevents more than 4 values and shows the 4 entered into the log (in the fiddle I change the console.log by an alert).
I solved it by storing the 4 values into a variable and if the user enters more than 4 values restore the textbox value with the variable value:
http://fiddle.jshell.net/6czXu/7/
var vals;
function CheckLength(val, key) {
var keycode = (key.which) ? key.which : key.keyCode;
if (val.length < 5){
alert(val);
// Here store the 4 values
vals = val;
if((keycode == 8 || keycode == 46) && (keycode < 48 || keycode > 57))
return false;
}
else{
// Here we have more than 4 digits entered so
// we restore the prevously stored into vals
document.getElementById("timepick").value = vals;
return false;
}
}

Use the onkeypress event instead and everything should work fine. onkeyup is to late.
<input type="text" id="timepick" onkeypress="return CheckLength(this.value,event);" />

Related

Here is some JavaScript that is supposed to run on the keyup event, but only if the keycode is between 48 and 57. Here is the code [duplicate]

This question already has answers here:
keyCode values for numeric keypad?
(13 answers)
Closed 1 year ago.
$('#cnic1').keydown(function(){
if (event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 ||
event.keyCode == 13 || (event.keyCode == 65 && event.ctrlKey === true) )
return;
if((event.keyCode < 48 || event.keyCode > 57))//0-9
event.preventDefault();
var length = $(this).val().length;
if(length == 5 || length == 13)
$(this).val($(this).val()+'-');
});
My problem is that this code only runs in response to the numbers entered at the top of the keyboard, but does not run in response to numbers entered from the numeric keypad.
I'm thinking the answer must be that the numeric keypad has different keyCode values, but how do I find out what those are?
The numeric keypad does have different keyCode values. The following link gives a full table of keyCodes for your reference:
https://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes
Use this code and press the keys. keycodes will be on console log;
window.onload = function(){
addEventListener("keydown",function(e){
console.log(e.keyCode);
});
}
Change if condition as
if((event.keyCode < 48 || event.keyCode > 57)&&(event.keyCode < 96 || event.keyCode > 105))//0-9
$('#cnic1').keydown(function() {
if (event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 ||
event.keyCode == 13 || (event.keyCode == 65 && event.ctrlKey === true))
return;
if ((event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105)) //0-9
event.preventDefault();
var length = $(this).val().length;
if (length == 5 || length == 13)
$(this).val($(this).val() + '-');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="cnic1">

jQuery prevent writing letters and change comma to dot

I have tried to modify this code but it just wont work...probably some small mistake but i can't debug it :(
// replace , with . and block writing letters
$(document).on("keydown", ".amount", function () {
$(this).keydown(function(e) {
if(e.keyCode==188 || e.keyCode==110 || e.keyCode==108){
e.preventDefault();
$(this).val($(this).val() + '.');
}
var key = e.charCode || e.keyCode || 0;
return (key == 8 || key == 9 || key == 46 || key == 110 || key == 188 || key == 190 || (key >= 35 && key <= 40) || (key >= 48 && key <= 57) || (key >= 96 && key <= 105));
});
};
This is original code and it doesn't work on dynamic content
that is why i want to modify it!
How about just calling your ForceNumericOnly method when the user clicks into an input with .amount?
$(document).on('focus', '.amount', function(){
$(this).ForceNumericOnly();
});
https://jsfiddle.net/daveSalomon/r5n8xuhx/5/
You could (should) optimise it so it doesn't add the keydown handler again if it's already run the ForceNumericOnly code... something like:
$.fn.ForceNumericOnly = function() {
return this.each(function() {
if($(this).data('forceNumberOnly'){ return; }
$(this).data('forceNumberOnly',true);
...
});
};
https://jsfiddle.net/daveSalomon/r5n8xuhx/6/
There's no JS required - just use a number input:
<input class="amount" type="number">

JQuery to allow only numeric input in text box using key code

I am trying to allow only numbers [0-9] to be typed in a text box. If an alpha or special character is typed, I do not want it to be shown in the text box. Currently my code is as follows:
$('#TEXTBOX').on("keydown", function(event){
var keyCode = event.which;
if(!((keyCode > 47 && keyCode < 58) || (keyCode > 95 && keyCode < 106) || keyCode == 08)){
event.preventDefault();
}
});
I am having a few problems.
This function is still allows special characters [i.e (SHIFT + 1) gives !, (SHIFT + 2) gives #] I do not want these key combinations to allow insert into text box
I am using magic numbers. I would prefer not to use magic numbers and logic but this is the only way I was able to get the input validation to work.... are there any suggestions on other methods?
My main concern is my first problem with the special characters.
$('#TEXTBOX').on("keydown", function(event){
var keyCode = event.which;
var charCode = (event.charCode) ? event.charCode : ((event.keyCode) ? event.keyCode: ((event.which) ? evt.which : 0));
var char = String.fromCharCode(charCode);
var re = new RegExp("[0-9]", "i");
if (!re.test(char))
{
event.preventDefault();
}
});
Use as
$('#TEXTBOX').on("keydown", function(event){
if(event.shiftKey)
return false;
var keyCode = event.which;
if(!((keyCode > 47 && keyCode < 58) || (keyCode > 95 && keyCode < 106) || keyCode == 08)){
event.preventDefault();
}
});
$(document).ready(function() {
$("#txtboxToFilter").keydown(function (e) {
// Allow: backspace, delete, tab, escape, enter and .
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
// Allow: Ctrl+A
(e.keyCode == 65 && e.ctrlKey === true) ||
// Allow: home, end, left, right, down, up
(e.keyCode >= 35 && e.keyCode <= 40)) {
// let it happen, don't do anything
return;
}
// Ensure that it is a number and stop the keypress
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
}
});
});
Worked For me (Only Numbers are allowed)
var key = e.charCode || e.keyCode || 0;
alert(key);
if (key < 48 || key > 58)
return false;

event.keycode issue

i have a javascript code like below,
if (event.keycode != 37 && event.keycode != 39)
{
var phoneNumber = $('#phoneNumber').val();
if (phoneNumber.length < 1 && event.keyCode != 48)
$('#phoneNumber').val(0)
else if ((phoneNumber.length < 2 && event.keyCode == 48) )
event.preventDefault();
else
$('#phoneNumber').val(phoneNumber)
}
keycode 37 = left arrow, keycode 39 = right arrow but when i pressed these keys on keyboard condition which is between if block being executed, i am using chrome browser, also i used the if statement below,
if (event.keycode != 37 || event.keycode != 39)
{
var phoneNumber = $('#phoneNumber').val();
if (phoneNumber.length < 1 && event.keyCode != 48)
$('#phoneNumber').val(0)
else if ((phoneNumber.length < 2 && event.keyCode == 48) )
event.preventDefault();
else
$('#phoneNumber').val(phoneNumber)
}
urgent helps greatly appreciated,
Thanks everybody.
One issue is capitalization: it's keyCode, not keycode. Your code is using them inconsistently.

Is the shiftkey held down in JavaScript

I have written a JS function that only allow numbers to be entered. A copy of that function is below:
function NumbersOnly(e) {
var evt = e || window.event;
if (evt) {
var keyCode = evt.charCode || evt.keyCode;
//Allow tab, backspace and numbers to be pressed, otherwise return false for everything.
//(keyCode>=96 && keyCode<=105) are the numpad numbers
if ((keyCode >= 48 && keyCode <= 57) || (keyCode >= 96 && keyCode <= 105) || keyCode === 9 || keyCode === 8) {
}
else {
evt.returnValue = false;
}
}
}
This function works fine with all the numbers but my problem happens when the shift key is held down and one of the number keys is pressed. The value returned is one of the characters above the numbers. So for example if I hold down shift and press 7, '&' is returned but the keyCode is still 55!! I would have expected that to be different.
So my question is how do I check if the shift key is being held down.
I've tried the following check but this didn't work:
if (keyCode === 16) {
evt.returnValue = false;
}
else {
if ((keyCode >= 48 && keyCode <= 57) || (keyCode >= 96 && keyCode <= 105) || keyCode === 9 || keyCode === 8) {
}
else {
evt.returnValue = false;
}
}
I'm using ASP.NET 4.0.
Any help would be gratefully received.
Thanks in advance.
You can check if shift key is pressed using :
if(evt.shiftKey) {
... //returns true if shift key is pressed
Use event.key instead of charCode. No more magic numbers!
function onEvent(event) {
const key = event.key; // "a", "1", "Shift", etc.
if (isFinite(key)) { // Is number
// Do work
}
};
Mozilla Docs
Supported Browsers
use keypress for holding any key isntead of keydown

Categories

Resources