Allow 2 digit number after the decimal - javascript

Hi i am trying to restrict user to input 2 digit number after the decimal.The below functionality is working but i am not able to modify the last two digit.suppose I have entered number 3456.78 and i want to modify 3456.68 it is not allowing.
$('.PMT_AMT').keypress(function(event) {
var $this = $(this);
if ((event.which != 46 || $this.val().indexOf('.') != -1) &&
((event.which < 48 || event.which > 57) &&
(event.which != 0 && event.which != 8))) {
event.preventDefault();
}
var text = $(this).val();
if ((event.which == 46) && (text.indexOf('.') == -1)) {
setTimeout(function() {
if ($this.val().substring($this.val().indexOf('.')).length > 3) {
$this.val($this.val().substring(0, $this.val().indexOf('.') + 3));
}
}, 1);
}
if ((text.indexOf('.') != -1) &&
(text.substring(text.indexOf('.')).length > 2) &&
(event.which != 0 && event.which != 8) &&
($(this)[0].selectionStart >= text.length - 2)) {
event.preventDefault();
}
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<input type="text" class="PMT_AMT">

Here's one possibility that uses a regular expression. Save the old input value on keypress, and if the new value on keyup does not validate, reset to that old value.
You need to validate on keypress as well, because otherwise, if the user types very fast, an invalid value can be saved:
const re = /^\d+(\.\d{0,2})?$/;
let oldVal;
$('.PMT_AMT').keypress(function(event) {
const { value } = this;
if (re.test(value)) oldVal = value;
});
$('.PMT_AMT').keyup(function(event) {
const newVal = this.value;
if (!re.test(newVal)) this.value = oldVal;
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<input type="text" class="PMT_AMT">

This solution creates a prediction and tests the regular expression against that instead.
$('.PMT_AMT').keypress(function(event) {
if(!/^\d*(\.\d{0,2})?$/.test(
this.value.slice(0, this.selectionStart)
+ String.fromCharCode(event.which)
+ this.value.slice(this.selectionEnd)
)) event.preventDefault();
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<input type="text" class="PMT_AMT">

Why use jQuery and not just browser functionality?
<input type="number" step="0.01">
On submit the browser will check if the submitted value of the input field has maximum two decimals.

Related

Changing input fields

I got a situation in which, I am validating input type using jquery.
I have html drop down list which contains different parameters("select:first-child").
I am trying validating input box based on these parameters for this I have written following code in jquery.
For example-
If I select "Quantity" then input box should take only numbers.
If I select "TradeDate" then input box should take date.
Now problem is ,when I select parameter which has type date , datepicker appears to select date.
But when I select any other parameter having type numbers ,input still showing datepicker.
So, Where I am wrong ,I want each time this validation
Here var type[1] contains type of parameter eg. float,date,char etc.
$("#cond_div").children("select:first-child").change(function(event){
var temp = $(this).val();
var type = temp.split("_");
$("#cond_div").children("input").on("keypress keyup", function () {
if (type[1].localeCompare("date") == 0) {
$(this).datepicker();
}
else if (type[1].localeCompare("float") == 0) {
$(this).val($(this).val().replace(/[^0-9\.]/g, ''));
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
event.preventDefault();
}
}
else if (type[1].localeCompare("int") == 0) {
$(this).val($(this).val().replace(/[^0-9\.]/g, ''));
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
event.preventDefault();
}
}
});
});
Once you've transformed an input with the .datepicker() creator, it stays that way until you destroy it by calling .datepicker("destroy") function.
SOLVED...
Instead of going with tricky logic ,found a simple way
$(document).ready(function () {
$("#cond_div").children("select:first-child").change(function (event) {
var temp = $(this).val();
var type = temp.split("_");
console.log("->" + temp);
console.log("->" + type);
$("#cond_div").children("input").val("");
$("#cond_div").children("input").datepicker("destroy");
if (type[1].localeCompare("date") === 0) {
console.log(type[1]);
$("#cond_div").children("input").datepicker();
} else if (type[1].localeCompare("char") === 0) {
console.log(type[1]);
$("#cond_div").children("input").attr("type", "text");
} else if (type[1].localeCompare("float") === 0) {
console.log(type[1]);
$("#cond_div").children("input").attr("type", "number");
} else if (type[1].localeCompare("int") === 0) {
console.log(type[1]);
$("#cond_div").children("input").attr("type", "number");
}
});
});

How to restrict zero at second position

In the below code the text box is restricting zero at starting position. But I want to allow only one zero at first position but not more than one. here is the example
Eg:- 0.1012400==> correct
000.4545000==>not correct
0154==> correct
00154 ==> not correct
$('input#abc').keypress(function(e){
if (this.selectionStart == 0 && (e.which == 48 || e.which == 46 )){
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="abc">
You can simply test if there is 2 consecutive zero at the start and if yes you remove one:
$('input#abc').on('keypress keydown keyup',function(e){
var v = $(this).val();
if(v.length >=2 && v[0]=='0' && v[1]=='0') {
$(this).val(v.substring(1));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="abc">
UPDATE
Here is a code if you want to consider the minus sign at the start:
$('input#abc').on('keypress keydown keyup', function(e) {
var v = $(this).val();
if (v.length >= 2 && v[0] == '0' && v[1] == '0') {
$(this).val(v.substring(1));
} else if (v.length >= 3 && v[0] == '-' && v[1] == '0' && v[2] == '0') {
$(this).val('-' + v.substring(2));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="abc">
You could check the final string like
$('input#abc').on('change', function () {
console.log(this.value.indexOf('00') === 0);
});

How to restrict user to allow only numeric and optionally two decimal number

I need to restrict user input to allow only a integer or a two decimal number with a limit from 0 till 99999.99.
Tried with script but not succeed in all scenarios.
also, required this should work with mobile OS also.
$('#txtamount').keydown(function (event) {
if (event.which == 8 || event.which == 9 || event.which == 37 || event.which == 38 || event.which == 46) {
//event.preventDefault();
return true;
}
alert('final' + event.which);
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
return false;
event.preventDefault();
}
var text = $(this).val();
if ((text.indexOf('.') != -1) && (text.substring(text.indexOf('.')).length > 2)) {
return false;
event.preventDefault();
}
});
Tried with below stuff but, not working to restrict special chars.
http://jsfiddle.net/jquerydeveloper/LmHkD/
Instead of using keycode detection, probably better to use a regex and onchange, rather than keydown.
$(document).ready(function () {
$('input[name="number"]').change(function (e) {
var valueEntered = $(this).val()
var regex = /^[0-9]{1,5}(\.[0-9]{2})?$/
if (!regex.test(valueEntered)){
$(this).val(''); //set value to nil, consider also display message
}
});
});
I'd also modify the input type to be a number, rather than text:
<input name="number" type="number" value=" " />
JSFiddle: http://jsfiddle.net/LmHkD/259/
Note, this will just get you started, you may need to update the regex for your exact scenario

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.

Restrict input field to two decimals with jQuery

I have an input field which I want to restrict so that the user only can input a number with the maximum of two decimals. Want to do this using jQuery.
Could I use jQuery toFixed() function somehow?
Thanx!
An alternative approach with a regular expression:
$('#id').on('input', function () {
this.value = this.value.match(/^\d+\.?\d{0,2}/);
});
The id selector can be replaced by a css selector.
$('input#decimal').blur(function(){
var num = parseFloat($(this).val());
var cleanNum = num.toFixed(2);
$(this).val(cleanNum);
if(num/cleanNum < 1){
$('#error').text('Please enter only 2 decimal places, we have truncated extra points');
}
});
Here is a fiddle http://jsfiddle.net/sabithpocker/PD2nV/
Using toFixed will anyhow cause approximation 123.6666 -> 123.67
If you want to avoid approximation check this answer Display two decimal places, no rounding
A HTML5 solution:
<input type="number" step="0.01" />
Demo
If you want to style invalid inputs (some browsers do it by default), you can use :invalid selector:
input:invalid { box-shadow: 0 0 1.5px 1px red; }
Note this approach won't attempt to truncate the number automagically, but if the user enters more than two decimal digits, the input will become invalid, and thus the form won't be submitted:
<input type="text" name="amount1" id="amount1" class="num_fld Amt" onkeypress="return check_digit(event,this,8,2);" size="9" value="" maxlength="8" style="text-align:right;" />
The following function will restrict decimals according to your need of decimal places and also restrict more than one dot
function check_digit(e,obj,intsize,deczize) {
var keycode;
if (window.event) keycode = window.event.keyCode;
else if (e) { keycode = e.which; }
else { return true; }
var fieldval= (obj.value),
dots = fieldval.split(".").length;
if(keycode == 46) {
return dots <= 1;
}
if(keycode == 8 || keycode == 9 || keycode == 46 || keycode == 13 ) {
// back space, tab, delete, enter
return true;
}
if((keycode>=32 && keycode <=45) || keycode==47 || (keycode>=58 && keycode<=127)) {
return false;
}
if(fieldval == "0" && keycode == 48 ) {
return false;
}
if(fieldval.indexOf(".") != -1) {
if(keycode == 46) {
return false;
}
var splitfield = fieldval.split(".");
if(splitfield[1].length >= deczize && keycode != 8 && keycode != 0 )
return false;
}else if(fieldval.length >= intsize && keycode != 46) {
return false;
}else {
return true;
}
}
}
$("#myInput").focusout(function() {
if ($(this).val().length > 2 || isNaN(Number($(this).val())) {
alert("Wrong number format");
}
});
Try this for all symbols:
inputField.value.replace(/(\...)(.)/, "$1");
or this for numbers:
inputField.value.replace(/(\.[0-9][0-9])([0-9])/, "$1");
I found this method here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Example:_Switching_words_in_a_string
<input type="text" id="decCheck" onkeyup="decimalCheck();"/>
<script>
function decimalCheck(){
var dec = document.getElementById('decCheck').value;
if(dec.includes(".")){
var res = dec.substring(dec.indexOf(".")+1);
var kl = res.split("");
if(kl.length > 1){
document.getElementById('decCheck').value=(parseInt(dec * 100) /
100).toFixed(2);
}
}
}
</script>
A similar solution with a backspace hit on reaching more than 2 decimal places.
function limitDec(id) {
// find elements
var amt = $("#testdec")
// handle keyup
amt.on("keyup", function() {
if (isNaN(amt.val())) {
amt.val(0);
}
if (amt.val().indexOf(".") > -1 && (amt.val().split('.')[1].length > 2)) {
amt.val(amt.val().substring(0, amt.val().length - 1));
}
})
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<input type="text" id="testdec" onkeyup="limitDec(this.id)" />

Categories

Resources