detect when pressing the deleted key using jquery - javascript

I am doing a calculator program using jquery program. In the following code I need to capture the delete key.
$("body").on("keydown",function(evt) {
var ChCod = (evt.which) ? evt.which : event.keyCode
strvalue=String.fromCharCode(ChCod);
if (ChCod > 31 && (ChCod < 48 || ChCod > 57) && (ChCod!=43) && (ChCod!=45) && (ChCod!=42) && (ChCod!=47) && (ChCod!=61) && (ChCod!=13) && (ChCod!=46)) {
return false;
}
else
{
if(ChCod==43 || ChCod==45 || ChCod==42 || ChCod==47 || ChCod==61 || ChCod==13|| ChCod==46)
{
if(ChCod==46)
Dot();
else if(strvalue=='=' || ChCod==13)
Calculate();
else
Operate(strvalue);
}
else
AddDigit(strvalue);
return false;
}
});
If I am using keydown event, It will not correctly trigger the number. (eg: when I pressing the '1' it return 'a')

$("body").on("keyup",function(evt) {
Use key up event then you will get correct char value

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">

Strange .replace() behaviour in Chrome browser

<div>
<input type="text" class="allownumericwithdecimal"/>saadad
</div>
$(".allownumericwithdecimal").live("keypress keyup ", function (event) {
$(this).val($(this).val().replace(/[^0-9\.]/g, ''));
var text = $(this).val();
if (!((event.which >= 48 && event.which <= 57) || event.which == 8 || event.which == 46 || event.which == 110 || event.which == 0)) {
var text = $(this).val();
if ((text.indexOf('.') != -1) && (text.substring(text.indexOf('.'), text.indexOf('.').length).length > 2)) {
//event.preventDefault();
}
}
var text = $(this).val();
if ((event.which >= 48 && event.which <= 57) && (text.indexOf('.') != -1)) {
if ((text.substring(text.indexOf('.'), text.indexOf('.').length).length) > 2) {
//event.preventDefault();
}
if (event.which == 190) {
//event.preventDefault();
}
}
if (text.indexOf('.') != -1 && event.which == 190) {
if (text.match("^[0-9]+(\.[0-9]{0,2})?$")) {} else {
$(this).val('');
}
}
if (text.indexOf('.') == -1 && text.length > 7 && (event.which != 190 && event.which != 8 && event.which != 46 && event.which != 110 && event.which != 0)) {
event.preventDefault();
}
});
http://jsfiddle.net/Lx9h2smh/
The problem is If I type a value in textBox say 3434 and now I want to make it 35434 by putting cursor after 3 and pressing 5, it works fine in Firefox and IE but in chrome the 5 get added after value and it becomes 34345.
The culprit line is one which replace non numeric characters.
How to handle this issue??
Try this code, it runs. jsFiddle
I just do a test
if ( /[^0-9\.]/g.test($(this).val()) ) {
$(this).val($(this).val().replace(/[^0-9\.]/g,''));
}
Explain
You just make sure that the user enter the value of what you want. You replace if the entered value is not an integer. Your regex mean: "Those which are not integer or dot (.), replace them with an empty value". That why You need to make this test. Therefore, if the user enters the value you want, it doesn't do the action replace and it doesn't pass to the test.
$(".allownumericwithdecimal").live("keypress keyup ",function (event) {
var caretP= $(this).getCursorPosition();
$(this).val($(this).val().replace(/[^0-9\.]/g,''));
var text = $(this).val();
if (!((event.which >= 48 && event.which <= 57) || event.which ==8 || event.which ==46 || event.which ==110 || event.which ==0) )
{
var text = $(this).val();
if ((text.indexOf('.') != -1) && (text.substring(text.indexOf('.'), text.indexOf('.').length).length > 2)) {
//event.preventDefault();
}
}
var text = $(this).val();
if((event.which >= 48 && event.which <= 57) && (text.indexOf('.') != -1))
{
if((text.substring(text.indexOf('.'), text.indexOf('.').length).length)>2)
{
//event.preventDefault();
}
if(event.which==190)
{
//event.preventDefault();
}
}
if(text.indexOf('.') != -1 && event.which==190 )
{
if(text.match("^[0-9]+(\.[0-9]{0,2})?$")){
}
else{
$(this).val('') ;
}
}
if(text.indexOf('.') == -1 && text.length>7 && (event.which!=190 && event.which !=8 && event.which !=46 && event.which !=110 && event.which !=0)){
event.preventDefault();
}
$(this).selectRange(caretP,caretP);
});
(function($) {
$.fn.selectRange = function(start, end) {
return this.each(function() {
if (this.setSelectionRange) {
this.focus();
this.setSelectionRange(start, end);
} else if (this.createTextRange) {
var range = this.createTextRange();
range.collapse(true);
range.moveEnd('character', end);
range.moveStart('character', start);
range.select();
}
});
};
$.fn.getCursorPosition = function() {
var input = this.get(0);
if (!input) return; // No (input) element found
if (document.selection) {
// IE
input.focus();
}
return 'selectionStart' in input ? input.selectionStart:'' || Math.abs(document.selection.createRange().moveStart('character', -input.value.length));
}
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<div>
<input type="text" class="allownumericwithdecimal"/>saadad
</div>
kepress seems to be the culprit when I changed the fiddle to just use keyup the replacement happened correctly (though the cursor shifted to the end)
http://jsfiddle.net/Lx9h2smh/1/
Just remove the 'keypress' event keypress event is very similar to the keydown event. If you press a button keypress event cannot identify the character. In your code it takes as current input Empty so it replace the character.

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..

javascript : key validation

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

Categories

Resources