I've some issues with decimal input on iOS using the numeric keypad. I have the following HTML:
$('#number').keyup(function() {
$('#log').prepend('<p>Input: ' + $(this).val() + '</p>');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" inputmode="decimal" id="number">
<p>
Input as number:
<div id="log"></div>
</p>
This is working as expected in Chrome browser, Android etc., but on iOS there is some issues. If I set the Region to e.g. Denmark (comma decimal seperator) but the Language to English (UK) (point decimal seperator), the number pad gives me a comma decimal seperator, but I seems that the HTML/JS does not support this. If I input e.g. 12,3 the value of the input field becomes empty when I use the comma.
How can I fix this?
When Region is Denmark and Language is Danish, it's all working as expected.
The code and demo is available on this StackBlitz: https://decimal-input-ios.stackblitz.io
I found some workaround, you can replace , with . every time that it is being typed:
let prevNum = "";
$('#number').on("keyup", function (e) {
if (e.keyCode == 188) {
$(this).val(prevNum + ".");
}
prevNum = $(this).val();
$('#log').prepend('<p>Input: ' + $(this).val() + '</p>');
});
Can you please try to add lang="en" it should change by adding a lang attribute
<input type="number" inputmode="decimal" id="number" lang="en">
This is a cheat, but after reading several similar posts about it, I'm not sure you have too many options. If you don't need the (usually inconsequential) up/down ticks, you can just use a 'text' input with a pattern. The pattern will tell iOS to use the number pad despite this being a 'text' input.
$('#number').keyup(function(evt) {
$('#log').prepend('<p>Input: ' + $(this).val() + '</p>');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" inputmode="decimal" id="number" pattern="[0-9.,]+">
<p>Input as number:</p>
<div id="log"></div>
I cannot test since I do not own any IOS device...
But you said:
When Region is Denmark and Language is Danish, it's all working as expected.
So why not just change the whole page language on that specific input focus and restore it on blur? That would be:
$("#number").on("focus", function(){
$("html").attr("lang", "da");
});
$("#number").on("blur", function(){
$("html").attr("lang", "en");
});
It worths a try ;)
Use parseFloat() to make the value a float
$('#number').keyup(function() {
$('#log').prepend('<p>Input: ' + parseFloat($(this).val()) + '</p>');
});
<html lang="en-GB">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" inputmode="decimal" id="number">
<p>
Input as number:
<div id="log"></div>
</p>
</html>
So what i want to achieve is that after every fourth be replaced with space.
Like if i start writing on keypress on input 1234123412341234,
I want to achieve 1234 1234 1234 1234, when user types.
<input type="text" id="number" maxlength=19 />
And here is js
$('#number').on('keypress', function() {
if (this.value.length >= 4) {
this.value = this.value.slice(0, 4) + ' '+this.value.slice(5, 9);
}
So this code only creates one space after fourth, 1234 123412341234.
But how to do for the rest of input value ? Thanks in advance.
You could use replace and look for four characters.
console.log('1234123412341234'.replace(/.{4}/g, '$& '));
This might be what you are looking for
Note it bugs a bit when you type fast, i'm fixing it atm <-- Should be fine
$(function(){
$("input").keydown(function(){
if ((($(this).val().length+1) % 5)==0){
$(this).val($(this).val() + " ");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input />
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.
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));
}
});
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.