I have got a task to prevent keypress two digits after a decimal number.
My jquery file is
$(function(){
$('#name').bind('paste', function(){
var self = this;
setTimeout(function() {
if(!/^[a-zA-Z]+$/.test($(self).val()))
$(self).val('');
}, 0);
});
$('#salary').bind('paste', function(){
var self = this;
setTimeout(function() {
if(!/^\d*(\.\d{1,2})+$/.test($(self).val()))
$(self).val('');
}, 0);
});
$('.decimal').keyup(function(){
var val = $(this).val();
if(isNaN(val)){
val = val.replace(/[^0-9]./g,'');
if(val.split('.').length>2)
val =val.replace(/\.+$/,"");
}
$(this).val(val);
});
});
My html page is
<b>Name</b>
<input type="text" id="name" /><br/>
<b>Salary</b>
<input type="text" id="salary" class="decimal" />
here i want only write 2 digits after decimal,how can i do this?
You can see my code in http://jsfiddle.net/V6s4B/
You can handle the key event before keyup on keypress, if the input is not to our liking we can disable the event from occurring. Something like this:
Update
Unfortunately my original answer below fails on certain numbers that can't be represented accurately as a float. Here is another solution that checks the position of the '.' character against the length of the string with a handy helper function.
jsFiddle
$('.decimal').keypress(function (e) {
var character = String.fromCharCode(e.keyCode)
var newValue = this.value + character;
if (isNaN(newValue) || hasDecimalPlace(newValue, 3)) {
e.preventDefault();
return false;
}
});
function hasDecimalPlace(value, x) {
var pointIndex = value.indexOf('.');
return pointIndex >= 0 && pointIndex < value.length - x;
}
Original answer
jsFiddle
$('.decimal').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;
}
});
Note that parseFloat(newValue) * 100 % 1 > 0 evaluates to true if newValue contains a number that has more than 2 decimal places.
$("#salary").keyup(function(){
var number = ($(this).val().split('.'));
if (number[1].length > 2)
{
var salary = parseFloat($("#salary").val());
$("#salary").val( salary.toFixed(2));
}
});
http://jsfiddle.net/calder12/fSQpc/
Stop letters from going in the box, you'll have to put the two together I haven't time.
if (this.value.match(/[^0-9]./g)) {
this.value = this.value.replace(/[^0-9]./g, '');
return false;
}
Another Possible Solution(Demo):
Number.prototype.toFixedDown = function(digits) {
var n = this - Math.pow(10, -digits)/2;
n += n / Math.pow(2, 53); // added 1360765523: 17.56.toFixedDown(2) === "17.56"
return n.toFixed(digits);
}
$( function() {
$('.two-digits').keyup(function(){
if($(this).val().indexOf('.')!=-1){
if($(this).val().split(".")[1].length > 2){
if( isNaN( parseFloat( this.value ) ) ) return;
this.value = parseFloat(this.value).toFixedDown(2);
}
}
return this; //for chaining
});
});
This might be helpful to some. I mixed the answers of this guy, #Tats_innit
from https://stackoverflow.com/a/10514166/5382523 and #Rick Calder above.
EDIT
also from this guy, isJustMe from https://stackoverflow.com/a/17289322
for the parseFloat with "|| 0". Because if the input's field is null or zero "NaN" is shown and you can't delete it.
HTML
<input type="text" name="txt_prod_price" id="txt_prod_price" class="form-control price" maxlength="20" placeholder="">
JAVASCRIPT (JQUERY)
$('.price').keypress(function(event) {
if(event.which < 46 || event.which > 59) {
event.preventDefault();
} // prevent if not number/dot
if(event.which == 46 && $(this).val().indexOf('.') != -1) {
event.preventDefault();
} // prevent if already dot
var number = ($(this).val().split('.'));
if (number[1].length > 2)
{
var price = parseFloat($("#txt_prod_price").val()) || 0;
$("#txt_prod_price").val(price.toFixed(2));
}
});
the "price" is pre-defined.
Note: still have buggy inputs but still kickin'. (y)
More info about toFixed - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed
I did it this way: Provided a class allow-only-numbers, for your input then:
var numberOfDecimals = 2;
$(document).on("input", ".allow-only-numbers", function () {
var regExp = new RegExp('(\\.[\\d]{' + numberOfDecimals + '}).', 'g')
this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1').replace(regExp, '$1');
});
Related
I have got a task to prevent keypress two digits after a decimal number.
My jquery file is
$(function(){
$('#name').bind('paste', function(){
var self = this;
setTimeout(function() {
if(!/^[a-zA-Z]+$/.test($(self).val()))
$(self).val('');
}, 0);
});
$('#salary').bind('paste', function(){
var self = this;
setTimeout(function() {
if(!/^\d*(\.\d{1,2})+$/.test($(self).val()))
$(self).val('');
}, 0);
});
$('.decimal').keyup(function(){
var val = $(this).val();
if(isNaN(val)){
val = val.replace(/[^0-9]./g,'');
if(val.split('.').length>2)
val =val.replace(/\.+$/,"");
}
$(this).val(val);
});
});
My html page is
<b>Name</b>
<input type="text" id="name" /><br/>
<b>Salary</b>
<input type="text" id="salary" class="decimal" />
here i want only write 2 digits after decimal,how can i do this?
You can see my code in http://jsfiddle.net/V6s4B/
You can handle the key event before keyup on keypress, if the input is not to our liking we can disable the event from occurring. Something like this:
Update
Unfortunately my original answer below fails on certain numbers that can't be represented accurately as a float. Here is another solution that checks the position of the '.' character against the length of the string with a handy helper function.
jsFiddle
$('.decimal').keypress(function (e) {
var character = String.fromCharCode(e.keyCode)
var newValue = this.value + character;
if (isNaN(newValue) || hasDecimalPlace(newValue, 3)) {
e.preventDefault();
return false;
}
});
function hasDecimalPlace(value, x) {
var pointIndex = value.indexOf('.');
return pointIndex >= 0 && pointIndex < value.length - x;
}
Original answer
jsFiddle
$('.decimal').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;
}
});
Note that parseFloat(newValue) * 100 % 1 > 0 evaluates to true if newValue contains a number that has more than 2 decimal places.
$("#salary").keyup(function(){
var number = ($(this).val().split('.'));
if (number[1].length > 2)
{
var salary = parseFloat($("#salary").val());
$("#salary").val( salary.toFixed(2));
}
});
http://jsfiddle.net/calder12/fSQpc/
Stop letters from going in the box, you'll have to put the two together I haven't time.
if (this.value.match(/[^0-9]./g)) {
this.value = this.value.replace(/[^0-9]./g, '');
return false;
}
Another Possible Solution(Demo):
Number.prototype.toFixedDown = function(digits) {
var n = this - Math.pow(10, -digits)/2;
n += n / Math.pow(2, 53); // added 1360765523: 17.56.toFixedDown(2) === "17.56"
return n.toFixed(digits);
}
$( function() {
$('.two-digits').keyup(function(){
if($(this).val().indexOf('.')!=-1){
if($(this).val().split(".")[1].length > 2){
if( isNaN( parseFloat( this.value ) ) ) return;
this.value = parseFloat(this.value).toFixedDown(2);
}
}
return this; //for chaining
});
});
This might be helpful to some. I mixed the answers of this guy, #Tats_innit
from https://stackoverflow.com/a/10514166/5382523 and #Rick Calder above.
EDIT
also from this guy, isJustMe from https://stackoverflow.com/a/17289322
for the parseFloat with "|| 0". Because if the input's field is null or zero "NaN" is shown and you can't delete it.
HTML
<input type="text" name="txt_prod_price" id="txt_prod_price" class="form-control price" maxlength="20" placeholder="">
JAVASCRIPT (JQUERY)
$('.price').keypress(function(event) {
if(event.which < 46 || event.which > 59) {
event.preventDefault();
} // prevent if not number/dot
if(event.which == 46 && $(this).val().indexOf('.') != -1) {
event.preventDefault();
} // prevent if already dot
var number = ($(this).val().split('.'));
if (number[1].length > 2)
{
var price = parseFloat($("#txt_prod_price").val()) || 0;
$("#txt_prod_price").val(price.toFixed(2));
}
});
the "price" is pre-defined.
Note: still have buggy inputs but still kickin'. (y)
More info about toFixed - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed
I did it this way: Provided a class allow-only-numbers, for your input then:
var numberOfDecimals = 2;
$(document).on("input", ".allow-only-numbers", function () {
var regExp = new RegExp('(\\.[\\d]{' + numberOfDecimals + '}).', 'g')
this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1').replace(regExp, '$1');
});
i am trying to covert decimal places on type input field like
Number starts from 0.00
so at first place it will be 0.00 in input field
than i type 1 than it should become 0.01
than i type 2 than it should become 0.12
than 0 so it should become 1.20 and lastly
when i type 0 than it should become 12.00
0.01, 0.12, 1.20, 12.00.
I tried some methods which already given in SO but not successful.
Please suggest me another methods if possible. thank you.
i tried like this
$(document).on('keyup','.price',function(e){
var value = $(this).val();
if(value.length <= 6) {
if(e.which == 190 || e.which == 46 || e.which == 44 || e.which == 188){
var amountDots = 0;
var amountCommas = 0;
if(value.indexOf(',') > -1){
amountCommas = value.match(/,/gi).length;
}
if(value.indexOf('.') > -1){
amountDots = value.match(/./gi).length;
}
if((amountDots >= 1 && amountCommas >= 1) || amountCommas > 1 || value.length == 1){
$(this).val(value.substr(0,value.length - 1));
return false;
}
else{
$(this).val(value.substr(0, value.length - 1) + ',');
}
}
$(this).val(value/100); //here is the value will insert
} else {
$(this).val(value.substr(0,value.length - 1))
return false;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="price" />
Ok, totally different solution that works when deleting characters:
$(document).on('keypress','.price',function(e){
var char = String.fromCharCode(e.which);
if(isNaN(char)) char = '';
var value = $(this).val() + char;
value = value.replace('.','');
$(this).val((value/100).toFixed(2));
if(!isNaN(char)) return false;
}).on('keyup','.price',function(e){
var value = $(this).val();
value = value.replace('.','');
$(this).val((value/100).toFixed(2));
});
https://jsfiddle.net/14shzdo5/
With each new keystroke, assuming it's a number, append it to the end, multiply by 10 and display the result.
The following logic works for the basic scenario. You may have to separately handle clearing out the text input.
$(document).ready(function() {
$("#my-input").on('keyup', function(e) {
var v = String.fromCharCode(e.keyCode);
if (!isNaN(v)) {
var dv = $("#my-display").val();
$("#my-display").val(dv + '' + v);
$(this).val(($("#my-display").val() / 100).toFixed(2));
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<input type="text" id="my-input" />
<input type="hidden" id="my-display" />
How to validate in an Amount input field?
Allow minus (Negative) sign only once in the text box. For, eg, -10.00. Don't allow other special characters because it's an amount field.
It should not allow alphabet letters. Allow only numbers.
Decimal(.) should be only once in the text box.
I've wrote this just now based on your conditions, test it below:
Update:
Modified to work both on jquery and in javascript inline
// This is a middleware that takes as parameter "decimals" which is by default 2
currencyNumber = function(decimals) {
if (typeof decimals !== 'number') {
decimals = 2;
}
return function(e) {
var input = $(this instanceof Window ? e : e.currentTarget);
var value = $.trim(input.val());
var hasNegativeNumber = value.substr(0, 1) === '-' ? '-' : '';
var nextValue = value
.replace(/\.+/g, '.')
.replace(/[^0-9\.]+/g, '');
if (nextValue === '.' || (nextValue.length > 1 && nextValue === "00")) {
nextValue = '';
}
var dotsFound = nextValue.split('.').filter(function(i) {
return i.length;
});
var afterDot = '';
var beforeDot = '';
if (dotsFound.length > 1) {
beforeDot = dotsFound[0];
dotsFound.splice(0, 1);
afterDot = dotsFound.join('');
nextValue = +(beforeDot) + '.' + afterDot.substr(0, decimals);
}
if (nextValue.substr(nextValue.length - 1, 1) === '.') {
input.one('change', function() {
if (nextValue.substr(nextValue.length - 1, 1) === '.') {
nextValue = nextValue.substr(0, nextValue.length - 1);
input.val(hasNegativeNumber + nextValue);
}
$(this).off('change');
})
} else {
input.off('change')
}
input.val(hasNegativeNumber + nextValue);
};
}
// Here is where you call the middleware
$("#amount").on("keyup", currencyNumber(3));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="banner-message">
Test your number (bind is from jquery):
<input id="amount" type='text' />
<br /> Test your number (bind is from javascript inline):
<input id="amount-inline" onkeyup="currencyNumber(3)(this);" type='text' />
</div>
Edited: I guess this is what you are looking for. Found this in jsfiddle.net. No plugin needed.
HTML:
<input type="text" maxlength="10" id="myInput">
Javascript
var input = document.getElementById("myInput");
input.onkeypress = function(e) { e = e || window.event;
var charCode = (typeof e.which == "number") ? e.which : e.keyCode;
// Allow non-printable keys
if (!charCode || charCode == 8 /* Backspace */ ) {
return;
}
var typedChar = String.fromCharCode(charCode);
// Allow numeric characters
if (/\d/.test(typedChar)) {
return;
}
// Allow the minus sign (-) if the user enters it first
if (typedChar == "-" && this.value == "") {
return;
}
// In all other cases, suppress the event
return false;
};
I want to validate my input according following requirements:
value can be from 1.00 to 9999.99
value fractional part cannot have more than 2 digits
I have wrote following code:
html:
<input id="amount" maxlength="7" type="text" />
js:
$("#amount").on("keyup", function(){
var valid = /^[1-9]{1}\d{0,3}(\,\d{0,2})?$/.test(this.value),
val = this.value;
if(!valid){
console.log("Invalid input!");
this.value = val.substring(0, val.length - 1);
}
});
But if I clamps '0' it works bad.
Please help to fix.
JSFIDDLE
P.S.
If I press '0' for 3-4 seconds I see
expected result - all input input be clear
$("#amount").on("input", function(){
var valid = /^[1-9]{1}\d{0,3}(\.\d{0,2})?$/.test(this.value),
val = this.value;
if(!valid){
console.log("Invalid input!");
this.value = val.substring(0, val.length - 1);
}
});
http://jsfiddle.net/a2eqrquf/
My Regex isn't really on point, so someone might be able to tidy that up a bit more than I can. But that is working as it should.
This is what the number input was made for just use the following HTML:
<input id="money-input" type="number" value="1" min="1" max="9999.99" step="0.01">
If your want to restrict the number of decimals that can be entered you could simply add some JavaScript to round of the number:
(function() {
var input = document.getElementById('money-input');
input.addEventListener('blur', function() {
this.value = Math.round(this.value * 100) / 100;
});
})();
I have updated your regular expresion, so now it's working like you want.
Demo: http://jsfiddle.net/vY39r/391/
$("#amount").on("input", function(){
var valid = /^[0-9]{1}\d{0,3}(\.\d{0,2})?$/.test(this.value),
val = this.value;
if(!valid){
console.log("Invalid input!");
this.value = val.substring(0, val.length - 1);
}
});
hope it's helps.
$(".allownumericwithdecimal").live("keypress keyup ",function (event) {
var text = $(this).val();
$(this).val($(this).val().replace(/[^0-9\.]/g,''));
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();
}
});
$(".allownumericwithdecimal").live("blur",function (event){
var text = $(this).val();
if((text.indexOf('.') != -1)){
if((text.substring(text.indexOf('.'), text.indexOf('.').length).length)>2){
text = text.toString(); //If it's not already a String
text = text.slice(0, (text.indexOf("."))+3); //With 3 exposing the hundredths place
$(this).val(text);
}
}
});
this is what i use personally
How to allow only one "." in javascript during Keypress?
I have a code here:
function allowOneDot(txt) {
if ((txt.value.split(".").length) > 1) {
//here, It will return false; if the user type another "."
}
}
I will reiterate what I said in my comment before the answer:
And what if the user pastes in a bunch of periods? What if they edit the javascript in their console to completely ignore this check? Make sure you are handling validation correctly and not making too many simplifications.
Now that we're proceeding at our own risk, here's how you would not allow a user typing more than one . (period) in a textbox:
document.getElementById('yourTextboxIDHere').onkeypress = function (e) {
// 46 is the keypress keyCode for period
// http://www.asquare.net/javascript/tests/KeyCode.html
if (e.keyCode === 46 && this.value.split('.').length === 2) {
return false;
}
}
Working demo
If you really want to allow one dot, even in the event of a user pasting text inside it, you should use keyup, not keypress, and you could keep your last text value in case you need to restore it.
The drawback though, is that the input value will have already been changed, and you will see it getting corrected as you type.
(function() {
var txt = document.getElementById('txt');
var prevValue = txt.value;
function allowOneDot(e) {
var dots = 0;
var length = txt.value.length;
var text = txt.value;
for(var i=0; i<length; i++) {
if(text[i]=='.') dots++;
if(dots>1) {
txt.value = prevValue;
return false;
}
}
prevValue = text;
return true;
}
txt.onkeyup = allowOneDot;
})();
I solved this question for the multipurpose use of decimal, number & alphanumeric field types.
For field types 'number' and 'alphanum', parameter l (lower L) is the string length allowed. For type 'decimal', it specifies the allowed number of decimal places.
function allowType(e, o = 'number', l = false) {
let val = e.target.value;
switch (o) {
case 'alphanum':
if (l) {
val = val.substr(0, l).replaceAll(/[^0-9a-zA-Z]/gmi, '');
} else {
val = val.replaceAll(/[^0-9a-zA-Z]/gmi, '');
}
break;
case 'number':
if (l) {
val = val.substr(0, l).replaceAll(/[^0-9]/gmi, '');
} else {
val = val.replaceAll(/[^0-9]/gmi, '');
}
break;
case 'decimal':
let i = val.search(/\./gmi);
if (val.length === 1) {
val = val.replaceAll(/[^0-9]/gmi, '');
}
if (i >= 0) {
if (l) {
val = val.substr(0, i + 1) + val.substr(i).substr(0, l + 1).replaceAll(/\./gmi, '');
} else {
val = val.substr(0, i + 1) + val.substr(i).replaceAll(/\./gmi, '');
}
}
val = val.replaceAll(/[^0-9.]/gmi, '');
break;
}
e.target.value = val;
}
<input type="text" oninput="allowType(event, 'decimal', 2)" placeholder="decimal">
<input type="text" oninput="allowType(event, 'number', 10)" placeholder="number">
<input type="text" oninput="allowType(event, 'alphanum', 5)" placeholder="alphanumeric">
<input type="text" id="test" onkeyup="floatOnly(this);"/>
<script>
function floatOnly(i){
{
if ((i.value).length > 0){else{i.value = i.value.replace(".." , ".");i.value = i.value.replace("..." , ".");i.value = i.value.replace(/[^0-9\.]/g , "");}}else{i.value = i.value="0";}}<script>