How do I prevent commas in a number input in IE - javascript

A number input on Chrome
<input type="number" />
Does not allow commas, only numeric,"e", and "."
However, on IE11 the number input does allow commas (2,000)
Is there an HTML way to normalize this behavior across number inputs? Should I not use the number input? How do I account properly for regions?
Looking for either an HTML or JS solution
Thanks!

This is another IE issue.
As far as I know, the only way to fix this is using JS:
input.addEventListener("input", function () {
input.value = input.value.replace(/,/g, ".");
});
Note that in most regions, a comma is used as a decimal separator.

Related

How to preview the result of a beforeinput event?

Does the beforeinput event provide a convenient way to preview the result of a proposed modification so that it can be blocked if necessary for validation purposes?
I'm not looking for alternative ways to do input validation; I'm already well-aware of methods involving the keypress and input events, as well as HTML5 validation, etc.. Right now, I'm specifically looking into the beforeinput event to see what it offers.
So far, this is the best I've come up with:
document.getElementById("phone").addEventListener("beforeinput", function(e) {
if(!/^(\d{0,7}|\d{3}-\d{0,4}|)$/.test(e.target.value + (e.data ?? ""))) {
e.preventDefault();
}
return;
});
<input id="phone">
The text field in the above snippet should accept a simple 7-digit phone number with optional dash after the 3rd digit.
Notice that I'm appending the event's data property to the input's current value to create a preview of the modified value. This works fine if you only enter input sequentially. But if, for example, you type in all 7 digits and then arrow back to just after the 3rd and try to insert the dash, you can't do it, because the validation assumes you're at the end where a dash would be invalid. Other problems arise if you try to replace or delete a selection.
An accurate preview will be required to solve these problems. Is there a simple way to get one from the beforeinput event?
You'd have to get the selectionStart and selectionEnd to figure out how many characters were removed / replaced / etc, but yeah, pretty simple:
document.getElementById("phone").addEventListener("beforeinput", function(e) {
const nextVal =
e.target.value.substring(0, e.target.selectionStart) +
(e.data ?? '') +
e.target.value.substring(e.target.selectionEnd)
;
console.log(nextVal)
if(!/^(\d{0,7}|\d{3}-?\d{0,4}|)$/.test(nextVal)) {
e.preventDefault();
}
return;
});
<input id="phone">

get number value from input element in JQuery not works when float parts empty

I want to code a currency converter, and only integer and float are allowed.So i detect the input change and do some calculation.
html snippet is as below:
<input type="number" id="currency">
JS is:
$("#currency").on("input", function(e){
var value = this.value
console.log(value)
});
Everything works well except when input is "12.", the value is an empty string?
what i want is 12 actually. How to solve the issue? Any help would be appreciated.
JSfiddle of snippet
This is because you are using input type="number"which wont allow any input other than number(including floating numbers).
But you put string or char as input you will see empty log statement and on doing parseInt(this.value) it will log NaN.
So if you still want to give string/number as a input you can use input type="text"
<input type="text" id="currency">
Input type="number" means any number including float, integer and does not allow to enter text.
so the best solution might be Input type="text" and if you want precision you can get by toFixed method as below example
$("#currency").on("input", function(e){
var value = this.value
if(isNumeric(value)){
alert(parseInt(value));
}
else{
alert("text")
}
});
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="currency">
Your issue is related to your localization.
As everybody confirms, <input type="number"> allows to enter integers and float.
So when typing 12., why do you get an empty result while some others get 12?
Because their decimal point is dot, while yours is something else!
E.g.: on my own system, where decimal point is comma, I get an empty result when typing 12. and 12 when typing 12,.

$(this).val() not working in FireFox but works in Chrome

This is my problem. When I try to set the value of an input field in FireFox nothing happens. I don't get any errors. It simply just doesn't work. It is supposed to add two decimal places after the number. It works perfectly in Chrome. Here's my jQuery code...
$('input.drawer').on('blur', function() {
var number = parseFloat($(this).val());
var n = number.toFixed(2);
$(this).val(n);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input tabindex="1" class="drawer f-right m-left w50 right-text" type="number" placeholder="$0.00" />
I've tried using $(this).attr('value' n); but that doesn't work either.
So, it does "work", but Firefox simply formats the number differently, it truncates the 0s. If you do
$(this).val(6.00);
you will see that it shows 6.
If you do
$(this).val(6.50);
it will show 6.5 but also an error that it is not a valid value.
What's with the error?
The default step value of the input is 1 which makes Firefox only consider numbers as valid that are a multiples of that.
If you set step="0.01" then Firefox considers floating point numbers as valid.
But the formatting is still incorrect
However, this still won't show the decimals for whole numbers. I guess that's just how it is given that the spec doesn't seem to describe how the value should be formatted.
If the format is more important to you than the functionality of the number input, use a normal text input instead.
This has to do with how firefox treats the number input type. https://bugzilla.mozilla.org/show_bug.cgi?id=1003896
You can try text if that is an acceptable input type for you.
Having found the above citation everything below is only interesting but not useful
For example in Firefox vs Chrome check out
http://jsbin.com/coyuyipeca/edit?html,js,output
You'll see the value is indeed formatted correctly in the alert in FF but lost when pushed to the number field. Change the input to
<input tabindex="1" class="drawer f-right m-left w50 right-text" type="text" placeholder="$0.00" />
and you'll see it work. Of course you will lose the benefits of the number field (notably mobile inputs) so it depends on how important that functionality is to you.
Note: One odd thing I note is if you set the input to
<input tabindex="1" class="drawer f-right m-left w50 right-text" type="number" step=".01" placeholder="$0.00" />
You can use the increment button and get decimals, it only seems to be lost when jQuery sets the value. Not sure if this is an issue with jQuery or with FF
This seems to work for me in the following jsfiddle:
<input tabindex="1" class="drawer f-right m-left w50 right-text" type="number" placeholder="0.00" />
$('input.drawer').on('blur', function() {
var number = parseFloat($(this).val());
var n = number.toFixed(2);
$(this).val(n);
});
Which is your exact code. The only thing is you cannot input '$' symbol into a number field. That would fail. So for eg: '3.4512' gets truncated to '3.45' and set properly, but '$3.4512' just gets cleared when I try it.
https://jsfiddle.net/bz0os3kp/1/
Your code seems to work. It does truncate the trailing zeros in firefox however.
I found a work around that seems to work in Firefox. I change the type of input to number on focus giving me the proper keypad on mobile but then change the type back to text on blur giving me to two decimal places. See the code below...
$('input.drawer').on('blur', function(){
var number = parseFloat($(this).val());
var n = number.toFixed(2);
$(this).attr('type','text');
$(this).val(n);
});
$('input.drawer').on('focus', function(){
$(this).attr('type','number');
});

Regular Expression - +/- sign and decimal

I am trying to create a regular expression for decimal number and at the same time "-" or "+" sign to be optional at the start.
There are a lot of information about this, so I finished with this:
/^[+-]?\d+(\.\d+)?$/
So, I have tested this in the console using the test() function and it is working perfectly.
My question is more about where to do this check:
if the check is on keypress event I am able to use preventDefault() in order to "consume" the incorrect symbols but I am retrieving the text like this and have no access to the last entered symbol - $(event.target).val()
if the check is on keyup event I have access to the whole text, but I am not able to remove the incorrect symbol, because I do not know which is it, and where it was put in (using the mouse it can be put in the start or in the middle of a valid string)
I need to check combination of symbols, not validate the symbols only. For example:
- //invalid
- 1 //valid
1. //invalid
1.2 //valid
So, I guess I should the check when the whole sting is entered, but then, how two remove the incorrect characters? Removing the whole string on when it is invalid does not look right.
The below is one possible way to tell the user if there is anything wrong with their input as they keep entering. Click here for a sample demo.
In addition, we can also add a <div> listing the allowed characters/format. This in addition to letting the user know that there is something wrong, will also tell them what forms a valid input.
HTML:
<input id='ip' type='text'/>
JS:
var regex = new RegExp(/^[+-]?\s*\d+(\.\d+)?$/);
document.getElementById('ip').onkeyup = function(){
var inputVal = this.value;
if(!(regex.test(inputVal))) this.className='err';
else this.className='noerr';
}
CSS:
.noerr{
color: green;
}
.err{
color: red;
}
Note: HTML5 has inbuilt ways to validate input and also has pseudo-classes like :invalid and :valid to do the same as what the above example does. If you can use HTML5, try this sample. The second input field is done using HTML5 (no JS required).
HTML5:
<input id='iphtml5' pattern='[+-]?\s*\d+(\.\d+)?' type='text' />
CSS:
#iphtml5:valid{
color: green;
}
#iphtml5:invalid{
color: red;
}

Get value of <input type="number"> with JS when it contains non-numeric characters

This jsfiddle demonstrates the following issue.
The simplest example is:
<input id="number" type="number" value="1">
console.log(document.getElementById('number').value);
This logs 1 as expected. THIS however:
<input id="number" type="number" value="1A">
console.log(document.getElementById('number').value);
Just logs an empty string '', because of the non-numeric character in the value. Some devices+browsers (e.g. Chrome) allow you to enter non-numeric characters in these inputs.
This is annoying because I want the type="number" input for devices that support it (e.g. iPhone, iPad number keyboard). However I want to use javascript to stop dirty input from being entered - which requires fetching the value on keyup - then regex replacing the non-numeric chars.
It appears jQuery's .val() method gives the same result.
This is what I was looking for:
$('input[type=number]').keypress(function(e) {
if (!String.fromCharCode(e.keyCode).match(/[0-9\.]/)) {
return false;
}
});
I understand preventing user input can be annoying and this still allows invalid input such as 1.2.3
However in this situation it is exactly what I needed. Hopefully it will be of use to someone else. Thanks to #int32_t for the suggestion.
You're not supposed to use <input type=number> for things that are not numbers (in very mathematical senseā€”it won't work for phone numbers or zip codes either) and clearing of the value is deliberate.
You can test whether device supports type=number and attach your fallback only if it doesn't:
var input = document.createElement('input');
input.setAttribute('type','number');
if (input.type != 'number') { // JS property won't reflect DOM attribute
polyfill_number();
}
Alternatively (especially if your number is a zip code, serial number, etc.) you can use:
<input type=text pattern="[0-9]*">
and this will change the keyboard too.

Categories