jQuery: how to set fixed decimals for input field value - javascript

I have a basic input field in which an amount is to be filled in.
The field is formatted as text as it also has to work with older browser versions.
Is there a way I can use jQuery and/or Regex to set fixed decimals (2) to any number in this field ?
I tried the following but this doesnt change anything:
<input type="text" class="span6" id="amount" maxlength="12" name="amount" />
$('#amount').on('blur', function() {
var amount = $('#amount').val().replace(/^\s+|\s+$/g, '');
if( ($('#amount').val() != '') && (!amount.match(/^\d+$/) ) {
$('#amount').val( amount.toFixed(2) );
}
});
What I am looking for is a way to add two decimals to the input value if there are none and the input is a number.
Examples:
1000 should become 1000.00
1000.99 should stay 1000.99 as there are already two decimals.
Many thanks for any help with this, Tim.

I have created a fiddle, please check Fiddle
before using toFixed convert the amount to integer parseInt(amount).
Edit
Code
$('#amount').on('blur', function() {
var amount = $('#amount').val().replace(/^\s+|\s+$/g, '');
if( ($('#amount').val() != '') && (!amount.match(/^$/) )){
$('#amount').val( parseInt(amount).toFixed(2));
}
});

Related

Format input with regex

I have a input field which is a percent value, i am trying for it to display as % when not focused in and when focused in it will loose the %, also the input field needs to avoid chars on it. I'm using a type"text" input field with some jQuery.
$(document).ready(function() {
$('input.percent').percentInput();
});
(function($) {
$.fn.percentInput = function() {
$(this).change(function(){
var c = this.selectionStart,
r = /[^0-9]/gi,
v = $(this).val();
if(r.test(v)) {
$(this).val(v.replace(r, ''));
c--;
}
this.setSelectionRange(c, c);
});
$(this).focusout(function(){
$(this).val(this.value + "%");
});
$(this).focusin(function(){
$(this).val(this.value.replace('%',''));
});
};
})(jQuery);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="percent" value="2"></input>
<input class="percent" value="4"></input>
on the snippet it does not behave the same as on my app, not sure why but the intended result is for it to erase any char that is not a digit or "only" 1 % sign.
Would change this approach only slightly:
use keypress (and eventually paste) to block invalid characters
use parseFloat (or int if you don't allow decimals) to remove leading 0's --> '00009.6' => '9.6%'
However I'd use <input type="number"> (btw: </input> closing tag is invalid HTML)
these days with a % sign just after the input. (number type has better display on mobile)
(function($) {
$.fn.percentInput = function() {
$(this)
// remove formatting on focus
.focus(function(){
this.value = this.value.replace('%','');
})
// add formatting on blur, do parseFloat so values like '00009.6' => '9.6%'
.blur(function(){
var r = /[^\d.]/g,
v = this.value;
this.value = parseFloat(v.replace(r, '')) + '%';
})
// prevent invalid chars
.keypress(function(e) {
if (/[^\d.%]/g.test(String.fromCharCode(e.keyCode)))
e.preventDefault();
});
};
})(jQuery);
$(document).ready(function() {
$('input.percent').percentInput();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="percent" value="2%">
<input class="percent" value="4%">
It is my understanding that the snippet you provided is the desired behavior, but your app isn't behaving in the desired way you've demonstrated. So, the question is: what's different between this snippet and your app? Does your app throw any errors into the console?
When I encounter problems like this, I'll usually run my page through an HTML validator. Sometimes, invalid html can corrupt more than you'd think.
When I put your html into a standard HTML5 template, the validator finds these errors in your snippet:
Basically, it is saying that you don't need </input>. Do this instead:
<input class="percent" value="2">
<input class="percent" value="4">
Perhaps this is completely unrelated, but I thought I'd mention it. I'd put your actual app through the html validator to see if you find more errors that could be ultimately corrupting your javascript's ability to achieve the desired behavior showcased by your snippet.

How to automatically add comma on amount displayed in input field if the customer clicked a button with specified amount?

The customer may click a button with specified amount and the amount would display in input field. I'm trying to automatically add a comma on the displayed amount but it's only working if the amount is typed. What would be the easiest way to do it?
<input type="number" class="input-char-amo" id="d-total" step="10000" value="0" min='10000' max="5000000" / required>
https://codepen.io/Cilissaaa/pen/vYYGjYB
You could use toLocaleString() method. It returns a string with a language-sensitive representation of a number.
let n = 1000000;
n.toLocaleString(); //"1,000,000"
chek it once. Hope it helps.
I have found the solution on this link: Can jQuery add commas while user typing numbers?
$('input.number').keyup(function(event) {
// skip for arrow keys
if(event.which >= 37 && event.which <= 40) return;
// format number
$(this).val(function(index, value) {
return value
.replace(/\D/g, "")
.replace(/\B(?=(\d{3})+(?!\d))/g, ",")
;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input class="number">

Limit the input Field to take only numbers with range

I want to create a input field in html where can limit the users to enter a number only between the range -40 to 130.
The user can also enter decimal values
For example :
-40.2 (valid)
-40.23 (not Valid)
130(valid)
130.1 (not Valid)
So the input should be able to take in any number between the range and should only accept decimal place fixed to 1.
Any suggestions or help is highly appreciated
thanks in Advance
You can use an input of type number with the attributes min max and step like this :
<form action="">
<input type="number" min="-40" max="130" step="0.1" id="input"/>
<button type="submit">Ok</button>
</form>
I provide a JSFiddle here. When you try to submit the form, the html5 validation displays a message if the number is out of the bounds or with more than one decimals.
JSFiddle
as Xartok told You can use an input of type number with the attributes min max and step but if the user is keying in the input its a bit hard from my experience. what i did was like this.
onkeypress is used to allow users to only key in integers with decimal only.
ng-blur is used to trigger changeDecimal function to do the validation/rounding up to fixed decimal places
<form>
<input type="text" id="input" onkeypress="return event.charCode >= 45 && event.charCode <= 57 && event.charCode!=47" ng-model="input1"ng-blur="changeDecimal()" />
<button type="submit">Ok</button>
</form>
and from the controller side what i did was this :
1st i parse the input to float and fix it to 1 decimal place.
then i made a condition to check the range if it is within the range, the input is replaced with the new value else an alert is returned.
in the else section i did a small check if the input is blank or not a number then replace with a default value (to avoid a loop of alert if the input is left blank)
app.controller('MainCtrl', function($scope) {
$scope.changeDecimal = function (){
temp = parseFloat($scope.input1).toFixed(1);
if (temp > -40 && temp < 130 && !isNaN(temp)){
$scope.input1= temp;
}else{
alert("value out of range ");
if (isNaN (temp) || temp == null || !angular.isDefined(temp)){
$scope.input1=0;
}
}
}
});
If you plan to use the input type as number what you can do is set a condition for you submit button (ng-disable). the button is disabled until the condition is met.
here is the sample from Plunker

Convert int with starting zeros to string to check length

I have an html input type="number" field in an html page. like this:
<input type="number">
To validate the form I need to check that the length of this field is exactly 3. To do this I convert the number to String and execute the length() function.
The problem comes when the number starts with a zero. like 065
In that case the toString() method outputs a 65 with a length of 2
Do you have any idea on how to get the correct length of the number ?
I think that you would have to have your input type as text and then use JavaScript to get the length for validation. After that you could convert it to a number using the Number() function.
Change the input type to text and restrict the input with a pattern and maxlength:
<input type="text" pattern="\d*" maxlength="3">
You can solve this one of two ways:
When the user moves focus away from the field, remove the leading zeroes
In the validation, remove the leading zeroes then check the length
There is no need to convert to a number.
Removing leading zeroes when focus is lost:
function truncateNumericInput(event) {
event = event || window.event;
event.target = event.target || event.srcElement;
if (event.target.nodeName != "INPUT" || event.target.type != "number") {
return;
}
var input = event.target,
value = event.target.value;
input.value = value.indexOf(".") > -1
? value.replace(/^0{2,}/, "0")
: value.replace(/^0+/, "");
}
if (document.addEventListener) {
document.addEventListener("blur", truncateNumericInput, true);
} else {
document.attachEvent("focusout", truncateNumericInput);
}
JSFiddle: http://jsfiddle.net/67jyg1d9/
Removing leading zeroes during validation
var regex = /^0+/;
var value = input.value.replace(regex, "");
console.log(value.length <= 3)
<input type="number" name="quantity" min="0" max="999">
this takes care that only number can be entered and only till 999 that's 3 digits at max
You can solve your problem by using input type as number. You can build your logic by using overflow and underflow as shown below.
<input id="numtest" type="number" min="10" max="20" />
document.getElementById('numtest').validity.rangeOverflow
document.getElementById('numtest').validity.rangeUnderflow
or
document.getElementById('numtest').checkValidity();
rangeUnderflow: return true if value is less then min
rangeOverflow: return true if value is greater than max value.

Input mask for numeric and decimal

I realized a software application management invoicing after having tested my program I noticed the following error:
my table in sqlserver contains: price numeric (6,2)
the user of my program enter price as 555.00 is good.
but when he put 555555 it's error, so I need to specify the mask where the mantissa is optional 0 to 999 and the decimal part is programmable 2 or 3 according to choice of the user, I'm using JQuery Masked input plugin and I have not found good regular expression, please, help, I'm working with jsp / servlet.
You can use jquery numeric for numbers.
The current version does allow what you're looking for but someone has changed the code a little bit and it works:
HTML
<input class="numeric" type="text" />
JQuery
$(".numeric").numeric({ decimal : ".", negative : false, scale: 3 });
This is the whole source.
And I've prepared this fiddle so you can see how it works.
using jQuery input mask plugin (6 whole and 2 decimal places):
HTML:
<input class="mask" type="text" />
jQuery:
$(".mask").inputmask('Regex', {regex: "^[0-9]{1,6}(\\.\\d{1,2})?$"});
I hope this helps someone
You can do it using jquery inputmask plugin.
HTML:
<input id="price" type="text">
Javascript:
$('#price').inputmask({
alias: 'numeric',
allowMinus: false,
digits: 2,
max: 999.99
});
https://codepen.io/vladimir-vovk/pen/BgNLgv
Use tow function to solve it ,Very simple and useful:
HTML:
<input class="int-number" type="text" />
<input class="decimal-number" type="text" />
JQuery:
//Integer Number
$(document).on("input", ".int-number", function (e) {
this.value = this.value.replace(/[^0-9]/g, '');
});
//Decimal Number
$(document).on("input", ".decimal-number", function (e) {
this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');
});
or also
<input type="text" onkeypress="handleNumber(event, '€ {-10,3} $')" placeholder="€ $" size=25>
with
function handleNumber(event, mask) {
/* numeric mask with pre, post, minus sign, dots and comma as decimal separator
{}: positive integer
{10}: positive integer max 10 digit
{,3}: positive float max 3 decimal
{10,3}: positive float max 7 digit and 3 decimal
{null,null}: positive integer
{10,null}: positive integer max 10 digit
{null,3}: positive float max 3 decimal
{-}: positive or negative integer
{-10}: positive or negative integer max 10 digit
{-,3}: positive or negative float max 3 decimal
{-10,3}: positive or negative float max 7 digit and 3 decimal
*/
with (event) {
stopPropagation()
preventDefault()
if (!charCode) return
var c = String.fromCharCode(charCode)
if (c.match(/[^-\d,]/)) return
with (target) {
var txt = value.substring(0, selectionStart) + c + value.substr(selectionEnd)
var pos = selectionStart + 1
}
}
var dot = count(txt, /\./, pos)
txt = txt.replace(/[^-\d,]/g,'')
var mask = mask.match(/^(\D*)\{(-)?(\d*|null)?(?:,(\d+|null))?\}(\D*)$/); if (!mask) return // meglio exception?
var sign = !!mask[2], decimals = +mask[4], integers = Math.max(0, +mask[3] - (decimals || 0))
if (!txt.match('^' + (!sign?'':'-?') + '\\d*' + (!decimals?'':'(,\\d*)?') + '$')) return
txt = txt.split(',')
if (integers && txt[0] && count(txt[0],/\d/) > integers) return
if (decimals && txt[1] && txt[1].length > decimals) return
txt[0] = txt[0].replace(/\B(?=(\d{3})+(?!\d))/g, '.')
with (event.target) {
value = mask[1] + txt.join(',') + mask[5]
selectionStart = selectionEnd = pos + (pos==1 ? mask[1].length : count(value, /\./, pos) - dot)
}
function count(str, c, e) {
e = e || str.length
for (var n=0, i=0; i<e; i+=1) if (str.charAt(i).match(c)) n+=1
return n
}
}
Now that I understand better what you need, here's what I propose. Add a keyup handler for your textbox that checks the textbox contents with this regex ^[0-9]{1,14}\.[0-9]{2}$ and if it doesn't match, make the background red or show a text or whatever you like. Here's the code to put in document.ready
$(document).ready(function() {
$('selectorForTextbox').bind('keyup', function(e) {
if (e.srcElement.value.match(/^[0-9]{1,14}\.[0-9]{2}$/) === null) {
$(this).addClass('invalid');
} else {
$(this).removeClass('invalid');
}
});
});
Here's a JSFiddle of this in action. Also, do the same regex server side and if it doesn't match, the requirements have not been met. You can also do this check the onsubmit event and not let the user submit the page if the regex didn't match.
The reason for not enforcing the mask upon text inserting is that it complicates things a lot, e.g. as I mentioned in the comment, the user cannot begin entering the valid input since the beggining of it is not valid. It is possible though, but I suggest this instead.
Try imaskjs. It has Number, RegExp and other masks. Very simple to extend.
If your system is in English, use #Rick answer:
If your system is in Brazilian Portuguese, use this:
Import:
<script
src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.15/jquery.mask.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.inputmask/3.2.6/jquery.inputmask.bundle.min.js"></script>
HTML:
<input class="mask" type="text" />
JS:
$(".mask").inputmask('Regex', {regex: "^[0-9]{1,6}(\\,\\d{1,2})?$"});
Its because in Brazilian Portuguese we write "1.000.000,00" and not "1,000,000.00" like in English, so if you use "." the system will not understand a decimal mark.
It is it, I hope that it help someone. I spend a lot of time to understand it.

Categories