javascript : key validation - javascript

im using javascript to validate keys in textbox. it is not working :(
function numeric(e) {
return ((e.keyCode == 8) ||
(e.keyCode == 9) ||
(e.keyCode > 47 && e.keyCode < 58) ||
(e.keyCode > 36 && e.keyCode < 41) ||
(e.keyCode == 46) ||
(e.keyCode > 95 && e.keyCode < 106) ||
e.keyCode == 190 ||
e.keyCode == 110);
}
help me...

function numeric(e) {
e = e || window.event;
keycode = e.keyCode || e.which;
if(keycode === 13){
alert("cheese");
}
}

I know that in I.E. you can set event.keyCode=0 to suppress the key appearing in the control. But I think you need to trap the onkeydown. Firefox might have an equivalent. This is good because it prevents the key actually "arriving" at the control.
Also keep in mind that you might need to handle combinations of Shift + key and alt + key.
a good debug technique for this sort of thing is to say windows.status = event.keyCode,
and you can see what the keycode is as you type it...

Just try out the following code. I have checked F5 keycode, you can check as you want
function disableKey(event)
{
if (!event) event = window.event;
if (!event) return;
var keyCode = event.keyCode ? event.keyCode : event.charCode;
if (keyCode == 116) {
showMsg("This functionality is disabled.");
window.status = "F5 key detected! Attempting to disabling default response.";
window.setTimeout("window.status='';", 2000);
// Standard DOM (Mozilla):
if (event.preventDefault) event.preventDefault();
//IE (exclude Opera with !event.preventDefault):
if (document.all && event && !event.preventDefault) {
event.cancelBubble = true;
event.returnValue = false;
event.keyCode = 0;
}
return false;
}
}
function setEventListenerForFrame(eventListener)
{
document.getElementById('your_textbox').onkeydown = eventListener;
//frames['frame'].document.onkeypress = eventListener;
}
<body onload="setEventListener(disableKey);">

Try this if you want a numbers only textbox:
function numbercheck(event) {
var unicode = event.charCode; var unicode1 = event.keyCode; if (navigator.userAgent.indexOf("Firefox") != -1 || navigator.userAgent.indexOf("Safari") != -1) {
if (unicode1 != 8) {
if ((unicode >= 48 && unicode <= 57) || unicode1 == 37 || unicode1 == 39 || unicode1 == 35 || unicode1 == 36 || unicode1 == 9 || unicode1 == 46)
{ return true; }
else
{ return false; }
}
}
if (navigator.userAgent.indexOf("MSIE") != -1 || navigator.userAgent.indexOf("Opera") == -1) {
if (unicode1 != 8) {
if (unicode1 >= 48 && unicode1 <= 57)
{ return true; }
else
{ return false; }
}
}
}
And in your textbox call it on the onkeypress event:
onkeypress="return numbercheck(event)"

Related

Disable all keys but copy paste combination

I am writing a code for number field where i have disabled all keys except number keys
function doValidation(event) {
var charCode = event.keyCode;
if (charCode != 190 && charCode != 40 && charCode != 39 && charCode != 38 && charCode != 37 && charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57) && (charCode < 96 || charCode > 105))
return false;
}
<input type="text" onkeydown="doValidation(event)">
Now i want to enable ctrl+c and ctrl+v in this funtion.
you can do this like below :)
var is_ctrl_pressed = false;
$('#number_input').on('keydown', function(e) {
var code = e.which;
if ((code > 47 && code < 59) || (code > 95 && code < 106) || (is_ctrl_pressed && (code == 67 || code == 86))) {
return true;
} else if (code == 17) {
is_ctrl_pressed = true;
} else {
return false;
}
});
$('#number_input').on('keyup', function(e) {
if (e.which == 17) {
is_ctrl_pressed = false;
}
});
Hope this will be helpful.
$('input[type="number"]').keypress(function(e){
//Numbers 47 to 57 are the key code of digit 0 to 9.
if (![48,49,50,51,52,53,54,55,56,57].includes(e.keyCode)){
e.preventDefault();
}
});
// Disable Right click
document.addEventListener('contextmenu', event => event.preventDefault());
// Disable key down
document.onkeydown = disableSelectCopy;
// Disable mouse down
document.onmousedown = dMDown;
// Disable click
document.onclick = dOClick;
function dMDown(e) { return false; }
function dOClick() { return true; }
function disableSelectCopy(e) {
// current pressed key
var pressedKey = String.fromCharCode(e.keyCode).toLowerCase();
if ((e.ctrlKey && (pressedKey == "c" || pressedKey == "x" || pressedKey == "v" || pressedKey == "a" || pressedKey == "u")) || e.keyCode == 123) {
return false;
}
}

Need help restricting a js function(that restricts invalid chars) to a particular input type

Hi i would like to restrict a function that allows only, numbers, back space and left & right arrow keys to inputs with number type, because when i implement it, it also affects my text inputs.
<script>
function chars(evt){
var key = window.event ? event.keyCode : event.which;
if (event.keyCode == 8 || event.keyCode == 46
|| event.keyCode == 37 || event.keyCode == 39) {
return true;
}
else if ( key < 48 || key > 57 ) {
return false;
}
else return true;
}
</script>
Assign an id to your <input>. Add an event listener to it, like :
function getKeyCode() {
var key = window.event ? event.keyCode : event.which;
if(event.keyCode == 8 || event.keyCode == 46
|| event.keyCode == 37 || event.keyCode == 39) {
console.log(true);
//return true;
} else if (key < 48 || key > 57) {
console.log(false);
// return false;
} else {
console.log(true);
// return true;
}
}
var el = document.getElementById("myInput");
el.addEventListener("keypress", getKeyCode);
<input type="text" id="myInput">

JQuery : Keypress not working on first press

This is my code
$(currentClass).keypress(function (e) {
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
return false;
}
});
The only problem with this is that, every time I hit a key for the first time regardless a letter or a number, it shows up in my content editable span tag. However, the second time I hit a letter key the code works, it only accepts number. I have no idea what is wrong with this code in the first pressing of keys.
Use JQuery's .on() method.
$(currentClass).on("keypress",function (e) {
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
return false;
}
});
This is what I used
if ($.inArray($event.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
// Allow: Ctrl+A
($event.keyCode == 65 && $event.ctrlKey === true) ||
// Allow: home, end, left, right
($event.keyCode >= 35 && $event.keyCode <= 39)) {
// let it happen, don't do anything
return;
}
// Ensure that it is a number and stop the keypress
if (($event.shiftKey || ($event.keyCode < 48 || $event.keyCode > 57)) && ($event.keyCode < 96 || $event.keyCode > 105)) {
$event.preventDefault();
}
I was able to solve the problem with this. If their suggestion is not working try this.
Bind Properly your events
$(document).ready(function(){
$(body).on("keypress","currentClass",function (e) {
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
return false;
}
});
});
$(currentClass).on('keypress', function (e) {
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
e.preventDefault();
alert("pressed");
return false;
}
});
event - on
This might helps you :)

Key Press Event In Jquery

I have many input types in the form .Now i want that the user can enter only integer values in the input types.The input can be like this 110.00 only two values after ..But i am not able to get this features.
I have done with the interger input but i am not getting how can we do this :
Code
$(".amount_class").live("keypress",function(e){
var charCode = (e.which) ? e.which : e.keyCode;
var Enteted = String.fromCharCode(e.which).toLowerCase();
if ((charCode >= 48 && charCode <= 57) || charCode == 8 || charCode == 9 || charCode == 37 || charCode == 39 || (charCode == 46 && Enteted != '.'))
return true;
else
return false;
});
The values are amount and it can be decimal but not more than two after decimal sign.Please help me
I have done this and working fine for me :
$('.salary').live("keypress",function(e) {
var charCode = (e.which) ? e.which : e.keyCode;
var Enteted = String.fromCharCode(e.which).toLowerCase();
if(!((charCode >= 48 && charCode <= 57) || charCode == 8 || charCode == 9 || (charCode == 37 && Enteted !='%') || charCode == 39 || charCode == 46)) {
e.preventDefault();
}
if(charCode == 46 && $(this).val().indexOf('.') != -1 && Enteted ==".") {
e.preventDefault();
} // prevent if already dot
if(charCode == 46 && Enteted =="." && !$(this).val()) {
e.preventDefault();
}
if($(this).val().indexOf('.')!=-1){
if($(this).val().split(".")[1].length >= 2){
if(charCode != 8 && charCode != 46) e.preventDefault();
if( isNaN( parseFloat( this.value ) ) ) return;
this.value = parseFloat(this.value).toFixed(2);
}
}
return this;
});
Use as below
HTML
<input type="text" id="checkDecimal" class="decimal" />
JS
$(function () {
$('#checkDecimal').bind('paste', function () {
var self = this;
setTimeout(function () {
if (!/^\d*(\.\d{1,2})+$/.test($(self).val())) $(self).val('');
}, 0);
});
$('#checkDecimal').keypress(function (e) {
var character = String.fromCharCode(e.keyCode)
var newValue = this.value + character;
if (isNaN(newValue) || parseFloat(newValue) * 100 % 1 > 0) {
e.preventDefault();
return false;
}
});
});
have a look here.
Regex - /^\d+(\.\d{0,2})?$/g;
i have experimented here
<!DOCTYPE html>
<html>
<head>
<script
src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$('#input_field').keyup(function(e) {
var regex = /^\d+(\.\d{0,2})?$/g;
if (!regex.test(this.value)) {
this.value = '';
}
});
});
</script>
</head>
<body>
<input type= "text" id = "input_field" name ="input_field" value=""/>
</body>
</html>
The logic is every time a user entering a number you have to check two things.
Has the user entered decimal point?
Are the decimal places more than two?
For the first one you can use $(this).val().indexOf('.') != -1For the second one you can use $(this).val().substring($(this).val().indexOf('.'), $(this).val().indexOf('.').length).length > 2
Here is the code:
$('.amount_class').keypress(function (event) {
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
event.preventDefault();
}
var text = $(this).val();
if ((text.indexOf('.') != -1) && (text.substring(text.indexOf('.')).length > 2)) {
event.preventDefault();
}
});
And the DEMO
Simply use
value.toFixed(2);
thats it..

jquery keydown for only digits

i have an input box that is for payments, and i want to only allow number like x.xx, of course xxxx.x will work or xxxxx
i have the setup pretty much working minus some weird behavior. if the numbers 1 and 2 after the decimal can be 2 digits long (works) but if i press 3-9 then it only allows one of that digit. also 0's to the right of the decimal are being allowed infinitely.
heres what im working with. also i want to only allow the enter button and when its pressed then run a function
$('#money-button-input-box').keydown(function(event) {
var str = $(this).val()
if(str.length >= 1){
var rightHalf = str.split('.')[1];
if(rightHalf >= 3 && event.keyCode != 8 ){
event.preventDefault();
}
}
if( (event.keyCode == 190 || event.keyCode == 110) && str.replace(/[^.]/g, "").length >= 1 ){
event.preventDefault();
}
allowOnlyNumbers(event);
if (event.keyCode == 13) {
if($(this).val() == '')return;
enterPayment($(this));
}
});
and the function
function allowOnlyNumbers(events){
// Allow: backspace, delete, tab, escape, and enter
if ( events.keyCode == 46 || events.keyCode == 8 || events.keyCode == 9 || events.keyCode == 27 || events.keyCode == 13 ||
// allow decimals
events.keyCode == 190 || events.keyCode == 110 ||
// Allow: Ctrl+A
(events.keyCode == 65 && events.ctrlKey === true) ||
// Allow: home, end, left, right
(events.keyCode >= 35 && events.keyCode <= 39)) {
// let it happen, don't do anything
return;
} else {
// Ensure that it is a number and stop the keypress
if (events.shiftKey || (events.keyCode < 48 || events.keyCode > 57) && (events.keyCode < 96 || events.keyCode > 105 )) {
events.preventDefault();
}
}
}
http://jsfiddle.net/Qxtnd/
The problem of decimals is because you are using
rightHalf >= 3
which evaluates the actual number & not it's length, because javascript type-casts it to a number for the comparison. What you want instead is the number of digits, try
rightHalf.toString().length >= 2
Fiddle here http://jsfiddle.net/Qxtnd/1/
Edit
As long as rightHalf is a string you can do:
rightHalf.length >= 2
if rightHalf was a number you would get an exception doing that.
function isNumberKeyUp(event, obj, beforeLength, afterLength) {
var text = document.getElementById(obj).value;
var splitText = text.split('.');
if (splitText.length > 1 && splitText[1].length > afterLength) {
document.getElementById(obj).value = splitText[0] + "." + splitText[1].substring(0,2);
return false;
}
return true;
}
function isNumberKey(event, obj,beforeLength,afterLength) {
var keyCode1 = event.keyCode;
var keyCode = 0;
if (keyCode1 == 0)
keyCode = event.which;
else {
keyCode = keyCode1;
}
if ((keyCode >= 48 && keyCode <= 57) || keyCode == 46 || keyCode == 13 || keyCode == 27 || keyCode == 127 ) {
var text = document.getElementById(obj).value;
if (keyCode == 46 && keyCode1 == 0) {
if (text.toString().indexOf(".") != -1) {
return false;
}
}
if (keyCode == 46) {
if (text.toString().indexOf(".") != -1) {
return false;
}
}
var splitText = text.split('.');
if (splitText[0].length >= beforeLength) {
if (keyCode == 46 && text.toString().indexOf(".") == -1) {
return true;
} else if (text.toString().indexOf(".") != -1)
{
return true;
}
return false;
}
}
else {
return GetDefault(event);
}
return true;
}
function GetDefault(event) {
var keyCode = event.keyCode;
if (keyCode == 0)
keyCode = event.which;
if (keyCode == 8 || keyCode == 9 || keyCode == 35 || keyCode == 36 || keyCode == 37 || keyCode == 38 || keyCode == 39 || keyCode == 40 || keyCode == 46 || keyCode == 118) {
return true;
}
return false;
}
Below is the html to call this events
<input type="text" onkeyup="return isNumberKeyUp(event,'txtID',9,2);" onkeypress="return isNumberKey(event,'txtID',9,2);" required="required" id="txtID" maxlength="12" value="1.00" name="txtID">
Here's the FIDDLE
rightHalf.length >= 2
$('#money-button-input-box').keyup(function () {
$(this).val(FormatNumber($(this).val()));
});
function FormatNumber(val){
var split = val.split('.');
if (split.length>1) return OnlyNumbersAllowed(split[0])+'.'+OnlyNumbersAllowed(split[1]);
else return OnlyNumbersAllowed(split[0]);
}
function OnlyNumbersAllowed(val){
return val.replace(/\D/g, '');
}
http://jsfiddle.net/Qxtnd/7/
You could easly put this regex in any function, instead of writing what you have now.

Categories

Resources