onkeydown with jquery and javascript function - javascript

I have developing an ASP.NET MVC 5 Web App and I have this html:
<div class="group">
<input type="text"
class="productClass"
name="Configurations[0].RemainingCodes"
id="Configurations[0].RemainingCodes"
onkeydown='IsValidKey(event);'
required />
</div>
And this Javascript function:
function IsValidKey(e) {
e = e || window.event;
var code = e.keyCode;
return (e.keyCode >= 48 && e.keyCode <= 57) || e.keyCode == 8 || e.keyCode == 46 || (e.keyCode >= 96 && e.keyCode <= 105);
}
But it doesn't work although I can get keycode in code variable. I'm trying to allow only numbers [0..9] key and backspace, but I can type letters.
The first version was this:
And javascript:
function IsValidKey()
{
return (window.event.keyCode >= 48 && window.event.keyCode <= 57) || window.event.keyCode == 8 || window.event.keyCode == 46 || (window.event.keyCode >= 96 && window.event.keyCode <= 105);
}
But FireFox complains about window.event doesn't exist.
I need to be able to run this code on as much as possible browsers.
And this is not a duplicate because I'm getting the code in Firefox and the function allows to enter letters.
How can I fix this problem?

IsValidKey(this) does not pass in the event object, it is passing in the html element. To pass in the event you have to specify event like: IsValidKey(this,event). Also you have to use return in your inline js, otherwise you need to call evt.preventDefault() in your callback.
function IsValidKey(element,evt) {
var event = ((window.event) ? (window.event) : (evt));
return (event.keyCode >= 48 && event.keyCode <= 57) ||
event.keyCode == 8 ||
event.keyCode == 46 ||
(event.keyCode >= 96 && event.keyCode <= 105);
}
<input type="text" onkeydown='return IsValidKey(this,event);' />
Or instead of using inline js you could use addEventListener, or jQuery's .keydown method to add your listeners and the event object will get passed in automatically
document.querySelector("#inputID").addEventListener("keydown",IsValidKey);
//OR jQuery("#inputID").keydown(isValidKey);
function IsValidKey(evt) {
/*.... rest of code ....*/

You can use following code in Firefox:
key = event.which;

I always do it this way in jQuery and haven't had problems with browser support.
$(document).keydown(function (e) {
var c = e.which;
e.preventDefault;
return (c >= 48 && c <= 57) || c == 8 || c == 46 || (c >= 96 && c <= 105);
});
As to why Firefox is complaining about window.event - browsers have different event models, and as far as I know, window.event simply doesn't exist in Firefox.

Based on an answer that someone posted but he/she deleted it, this is my solution:
function IsValidKey(e) {
var c = e.which;
if (!((c >= 48 && c <= 57) || c == 8 || c == 46 || (c >= 96 && c <= 105)))
e.preventDefault();
}
HTML:
<div class="group">
<input type="text"
class="productClass"
name="Configurations[0].PkgRatio"
id="Configurations[0].PkgRatio"
onkeydown='IsValidKey(event);'
required />
</div>

What you need is to return the boolean in the onkeydown attribute:
onkeydown='return IsValidKey(event);'
If the event handler is returning false is blocking the propagation of the event, or the bubbling up.
See this answer too : https://stackoverflow.com/a/4379459/4768374

Related

How do write .keycode event dependent on not holding down other keys

I've got a function on my web app that fires when any letter or number is pressed. This can get quite annoying for power users though when something like CMD+R (OSX page refresh) is used.
Right now my js looks like:
$(document).bind('keydown',function(e){
if(e.keyCode >= 65 && event.keyCode <= 90 || e.keyCode >= 48 && event.keyCode <= 57) {
// doing stuff
}
});
How can I write my if statement so .keycode only works if any other key isn't being held down?
Success!
window.onkeydown = function (e) {
if (!e) e = window.event;
if (!e.metaKey) {
if(e.keyCode >= 65 && event.keyCode <= 90 || e.keyCode >= 48 && event.keyCode <= 57) {
// doing stuff
}
}
}
See it in action here: http://codepen.io/jeremypbeasley/pen/xbVoxY

JQuery textfield only accepts numbers as input, this works well but when I use my numpad it does not work

I want my JQuery code to only accept numbers as input in the textfield, this code is working well for me but soon discovered that if I used the numbers in my numpad it does not work. Any suggestions for this problem guys?
Here is my code:
<script type="text/javascript">
$(".txtboxToFilterNum").keydown(function(event) {
if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 0 || event.keyCode == 13 || event.keyCode == 27) {
// let it happen, don't do anything
}
else {
// Ensure that it is a NUMBER and stop the keypress
if (event.keyCode < 48 || event.keyCode > 57 ) {
event.preventDefault();
}
}
});
</script>
Do not check which key is pressed, but which content is given, it will be easier to check if the content are numbers only, and it will prevent many other things such as using copy and paste with letters (I guess this is not handled in your given code too)
working sample
HTML
<input type="text" class="textfield" value="" id="extra7" name="extra7" onkeypress="return isNumber(event)" />
Javascript
function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}

Why my condition is not satisfied?

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

validation not working in Firefox but works in IE,Chrome

I use the following java script function for integer validate which means the text box can allow to enter only the integer values alone.*It was work fine in Internet explorer and google chrome*.But I use this same function in FireFox the text box didn't allow to enter any characters in that which means it doesn't allow characters,numbers,space,anything else..How to solve this problem?
javascript function
$('.intValidate').live('keypress', function(event) {
var integervalidate = intValidate(event);
if (integervalidate == false)
return false;
});
function intValidate(event) {
if ( event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 13 ||(event.keyCode == 65 && event.ctrlKey === true) ||(event.keyCode >= 35 && event.keyCode <= 39))
{
return;
}
else
{
if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105 ))
{
event.preventDefault();
}
I use the class like,
<input type="text" id="abcd" style="width:30px" maxlength="2"class="intValidate""/>
Your problem is the inconsistent way that browsers use the keypress event.
Read this post to get a good explanation with an example of a work around.
You're examining keycodes in the keypress event. You should be looking at charCode values instead.

jQuery/JS Keycodes: Several keycodes in one IF statement

I'm trying to set up some keycodes for an app I'm working on but it really drives me crazy.
I'm trying to set up keycodes which would say, from keyCode 65 to 91 , 44 , 47 and few others, do function.
So I have this:
var e = event || evt;
if ((e.keyCode > 65 || e.Keycode < 91)){
// Do function
}
which works find. Now if I try to add another keycode it doesn't work.
This is what I tried:
if ((e.keyCode > 65 || e.Keycode < 91) && (e.keyCode == 44) && (e.keyCode == 47)){
Does someone help me to add different keycodes in one If statement?
Thanks alot
Try this
if (
// get all the keys between 65-90
(e.keyCode >= 65 && e.keyCode <= 90)
// or 44 or 47
|| e.keyCode == 44 || e.keyCode == 47)
{
// do stuff
}
If the conditional logic is tripping you up, I think you might be best served by thinking about the numbers you want to include (not exclude). Break them into ranges and put each range on its own line. Start with pseudo code:
if
// keys between 31-47
// or keys between 58-90
then
// do stuff
end
Then fill in the conditions:
if (
// keys between 31-47
(e.keyCode >= 31 && e.keyCode <= 47)
// or keys between 58-90
|| (e.keyCode >= 58 && e.keyCode <= 90)
)
{
// do stuff
}
If you want everything from 31 to 90 except for those from 48 through 57:
if (e.keyCode >= 31 && e.keyCode <= 90 && !(e.keyCode >= 48 && e.keyCode <= 57)) {
// whatever
}
Now that could be written equivalently as:
if (e.keyCode >= 31 && e.keyCode <= 47 || e.keyCode >= 58 && e.keyCode <= 90) {
// whatever
}
if ((e.keyCode > 65 && e.Keycode < 91) || e.keyCode == 44 || e.keyCode == 47){
//do stuff
}

Categories

Resources