Chrome clearing input type=number - html

In the latest release "47.0.2526.73" all my input type="number" are clearing every time that we try to type a float point number, example : 1.1
These inputs have a keyup event handler in jQuery to remove the leading zeros.
This code was working before the latest update.
Is there a bug?
-- UPDATE --
//Fix to leading zero decimals
$('input[type=number]').keyup(function (e) {
if (!this.value && (e.keyCode == 190 || e.keyCode == 110)) {
this.value = '0.';
}
});
This is the code that is not longer working

Change the step so it don't use the default '1' and uses a float. It will allow you to use float numbers and not only integers.
Ex: '0.1'

Looks like chrome is no longer allowing you to read/set the input value for number types using the keyup event when it is in the middle of the decimal point typing.
This is when the user type just '.', you cannot get the value '1.' or set it the same way in the event.
What I did was change the logic to:
$('input[type=number]').keyup(function (e) {
if (this.value) {
if (this.value.charAt(0) == '.')
{
this.value = '0' + this.value;
}
}
});
This is the only way that I have found to fix typing a number without the leading zero in the input box

Related

How to detect up and down clicks on html input[number]?

I have an html <input type="number"> box that has some custom validation logic. A valid value is any integer x where x < -100 OR x >= 100.
My goal is to implement this behavior:
when the user clicks on the native down arrow or presses the down arrow key and the current value is 100, the value changes to -101.
similarly when the user clicks on the native up arrow or presses the up arrow key and the current value is -101, the value changes to 100.
A few caveats:
Users must still be able to type numbers that fall within the invalid range since they may need to type 10 in order to type 109. And validation logic already occurs for this.
I am using angularjs, but I suspect that the solution is not going to be angular specific.
This is an internal application, meant for Chrome only, so browser specific answers are fine.
I think I have what you need, or at least I'm getting close:
window.onload = function() {
function changeNum(input, typing) {
var lower=-101, upper=100, x=parseInt(input.value), active=(input==document.activeElement);
if ((typing && String(Math.abs(x)).length>2 && lower<x&&x<upper) || (!typing && lower<x&&x<upper)) {
if (Math.abs(x-upper) < Math.abs(x-lower)) {input.value = (!active||typing?upper:lower);}
else {input.value = (!active||typing?lower:upper);}
}
}
document.getElementById("num").addEventListener("keyup",function(){changeNum(this,true);},false);
document.getElementById("num").addEventListener("change",function(){changeNum(this,false);},false);
};
<input type="number" id="num" value="100" />
jsfiddle: https://jsfiddle.net/9zz0ra35/4/
codepen: http://codepen.io/anon/pen/Ndqbog
When the user clicks on the input's up&down-buttons, the value flips over on the lower and upper threshold (-100 -> 100, 99 -> -101).
When the user types a value and then clicks outside the input, invalid values are changed to the closest threshold (-100 -> -101, 99 -> 100).
While typing, invalid values are also changed to the closest threshold, but only if the value.length is more than 2 chars (-100 -> -101).
This last one isn't as clean as the others, because it only works if both the lower and upper threshold have the same length (in this case 3 chars).
But if you need thresholds with different lengths, you can always change the String(Math.abs(x)).length>2 to an extra if-clause and first check whether the value is positive or negative, and then check for separate lengths.
I'm not sure if I'm getting what you want. Is it something like this?
var number = document.getElementById('number-input');
number.onchange = function(event) {
if(number.value > 100) {
number.value = -101;
} else if(number.value < -100) {
number.value = 101;
}
};
<input type="number" id="number-input">

Don't let a user type the period character in an HTML5 input type number

So right now the user is able to insert a decimal value in the number field of the HTML5 input type="number". I want to prevent that, so if a user types "5.1" it will insert "51" in the textbox.
Is there any way to do this? Thanks!
The definite answer is this:
function preventDot(e) {
var key = e.charCode ? e.charCode : e.keyCode;
if (key == 46) {
e.preventDefault();
}
}
And bind it on keypress
You can use a regular expression to find the characters that make the value a decimal value, and then delete them so that the value internally becomes an integer:
/[\.,]/

How to completely restrict decimal points from being entered in text input?

I have been searching through many HTML-related questions here and I am currently using the input tag pattern attribute to validate my inputs. This works by only allowing one or two numbers being input, and does not submit invalid data. However, I would prefer unwanted characters (decimal point and letters) to not be able to be put in the text box at all.
This will do it for you https://jsfiddle.net/DIRTY_SMITH/cfckvvzw/4/
updated fiddle to allow numbers in numlock to work too https://jsfiddle.net/DIRTY_SMITH/cfckvvzw/5/
<input ID="FirstName1" class="test" onkeydown="return Fname(event);">
<script>
function Fname(evt) {
evt = (evt) ? evt : event;
var charCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode : ((evt.which) ? evt.which : 0));
//checks for invalid keystrokes (numbers only)
if (charCode > 57 || charCode < 48) {
return false;
} else {
return true;
}
}
</script>

HTML5 input type number not working in firefox

I am using HTML5 input type=number. Its working perfectly in Chrome browser, but its not working in Firefox and IE9.
I want to increment the quantity by one i.e. step=1 and also I have set min=1.
I am using the following code:
<form action="" class="cart" method="post" enctype='multipart/form-data'>
<div class="quantity">
<input type="number" step="1" min="1" name="quantity" value="1" title="Qty" class="input-text qty text" />
</div>
<button type="submit" class="single_add_to_cart_button button alt">Add to cart</button>
</form>
Is there any patch or hack to make it work in Firefox and IE9. Or else, what could be the possible solution for that.
It is not supported in firefox or internet explorer, except for version 11 which has partial support. See this comparison matrix.
You can use the number polyfill shim to get support for unsupported browsers.
Alternately, you can use a textfield with a pattern="" attribute. Although it doesn't have the up and down buttons, it does validate for having the correct values:
<input type="text"
name="quantity"
pattern="[1-9]"
value="1"
required
title="Qty"
class="input-text qty text"
/>
You can alter the pattern to your quantity wishes, it is now set for a value ranging from 1 to 9. Also you can add up/down buttons with JS/jQuery that have hotkeys bound to them for a more number-field-like feel.
For React I have used a simple and clean implementation to forbid letters in Firefox/Safari/Chrome etc...
<input type="number" onKeyDown={(event) => checkIfNumber(event)} />
checkIfNumber(event) {
/**
* Allowing: Integers | Backspace | Tab | Delete | Left & Right arrow keys
**/
const regex = new RegExp(/(^\d*$)|(Backspace|Tab|Delete|ArrowLeft|ArrowRight)/);
return !event.key.match(regex) && event.preventDefault();
}
Allowing more keys:
By logging the event.key in the console you are able to check the actual value of the pressed key while then adding it to the regex using a pipe | symbol.
Keep in mind that this solution only allows Integers, if you want to allow floating numbers(decimals) use the following regex pattern
regex = new RegExp(/(^\d*\.?\d*$)|(Backspace|Tab|Delete|ArrowLeft|ArrowRight)/)
You can build and check your regex pattern here:
https://regex101.com/
The input type number is not supported yet in Firefox or IE9 (almost in IE10), so it will revert to input type text.
See this compatibility chart.
There's really no need for a "patch or hack" - a regular input field will work just fine. That's why it reverts to a text field. Whether or not it displays as an actual number field to the end-user is just a bonus to make it slightly more convenient. You should still be doing server-side checks on whatever value is sent to you, so allowing a user to just type in a number when their browser doesn't support the number type shouldn't harm anything.
It's not supported.
You can use javascript for the same result if you really need it.
There are lot of examples :
Increment value of textinput with jquery like spinner
I am using firefox, I had the same issue developing my input type number typing characters and spaces etc...
anyway I am using angular 2 in this example, it's almost similar to JavaScript, so you can use this code in every case :
here is the html :
<input class="form-control form-control-sm" id="qte" type="number" min="1" max="30" step="1" [(ngModel)]="numberVoucher"
(keypress)="FilterInput($event)" />
here is the function FilterInput :
FilterInput(event: any) {
let numberEntered = false;
if ((event.which >= 48 && event.which <= 57) || (event.which >= 37 && event.which <= 40)) { //input number entered or one of the 4 directtion up, down, left and right
//console.log('input number entered :' + event.which + ' ' + event.keyCode + ' ' + event.charCode);
numberEntered = true;
}
else {
//input command entered of delete, backspace or one of the 4 directtion up, down, left and right
if ((event.keyCode >= 37 && event.keyCode <= 40) || event.keyCode == 46 || event.which == 8) {
//console.log('input command entered :' + event.which + ' ' + event.keyCode + ' ' + event.charCode);
}
else {
//console.log('input not number entered :' + event.which + ' ' + event.keyCode + ' ' + event.charCode);
event.preventDefault();
}
}
// input is not impty
if (this.validForm) {
// a number was typed
if (numberEntered) {
let newNumber = parseInt(this.numberVoucher + '' + String.fromCharCode(event.which));
console.log('new number : ' + newNumber);
// checking the condition of max value
if ((newNumber <= 30 && newNumber >= 1) || Number.isNaN(newNumber)) {
console.log('valid number : ' + newNumber);
}
else {
console.log('max value will not be valid');
event.preventDefault();
}
}
// command of delete or backspace was types
if (event.keyCode == 46 || event.which == 8) {
if (this.numberVoucher >= 1 && this.numberVoucher <= 9) {
console.log('min value will not be valid');
this.numberVoucher = 1;
//event.preventDefault();
this.validForm = true;
}
}
}
// input is empty
else {
console.log('this.validForm = true');
this.validForm = false;
}
};
in this function I had to just let the keypress of numbers, direction, deletes enter.
To allow only number and points to be written in an input we have to get the value of the pressed key and compare it with a REGEX (test() method), otherwise the event isn't executed.
const input = document.getElementById("numberInput");
input.addEventListener("keypress", e => {
// If the input is empty and the key pressed is "0" nothing is printed
if (!e.target.value && e.key == 0) {
e.preventDefault();
} else {
// If the key pressed is not a number or a period, nothing is printed
if (!/[0-9.]/.test(keyValue)) {
e.preventDefault();
}
}
}
Also I created a function that allows writing a maximum of three whole numbers and two decimal numbers.
I hope it helps you.
I usually post information that has helped me or some solutions on my twitter (#PabloAndresValC)
input.addEventListener("keypress", e => {
const keyValue = e.key;
// If the input is empty and the key pressed is "0" nothing is printed
if (!e.target.value && keyValue == 0) {
e.preventDefault();
} else {
// If the key pressed is not a number or a period, nothing is printed
if (!/[0-9.]/.test(keyValue)) {
e.preventDefault();
} else {
// If the number has one or two whole numbers and a point, another
// point won't be printed
if (/[0-9]{1,2}[.]/.test(e.target.value) && keyValue == ".") {
e.preventDefault();
}
// If the number has one or two whole numbers and a point
else if (/[0-9]{1,2}[.]/.test(e.target.value)) {
// We can write up to two more numbers after the point
if (/[0-9]{1,2}[.][0-9]{2}/.test(e.target.value)) {
e.preventDefault();
}
}
// If there are 3 numbers and we press another, a point
// will be printed automatically
// And we can write up to two more numbers after the point
else if (/[0-9]{3}/.test(e.target.value) && keyValue != ".") {
e.target.value += ".";
if (/[0-9]{3}[.][0-9]{2}/.test(e.target.value)) {
e.preventDefault();
}
}
}
}
});
Note: The min attribute of the tag is not supported in Internet Explorer 9 and earlier versions, or in Firefox.
Note: The min attribute will not work for dates and time in Internet Explorer 10, since IE 10 does not support these input types.
Source: http://www.w3schools.com/tags/att_input_min.asp
Firefox 89.0 solves this problem.
I think this is the best practice in my previous projects experience.
This solution worked on Firefox, Safari and other not support input[type=number] realized browsers.
document.querySelector('#number-input').addEventListener('keydown', function(evt){
!/(^\d*\.?\d*$)|(Backspace|Control|Meta|a)/.test(evt.key) && evt.preventDefault()
})
<html>
<input type="number" id="number-input"/>
</html>
<input
type="text"
class="form-control"
#keypress="getMobileNumber($event)"
/>
//Function
function:getMobileNumber(e){
let char = String.fromCharCode(e.keyCode); // Get the character
if (/^[0-9]*$/.test(char)) return true;
// Match with regex
else e.preventDefault(); // If not match, don't add to input text
},

How can I make the HTML5 number field display trailing zeroes?

I have a field:
<input type='number' />
I'd like to punch in 0.50 without it “correcting it” to 0.5, so it would display 0.50.
I attached an on('change') event to the input you want to have trailing 0's
$('.number-input').on('change', function(){
$(this).val(parseFloat($(this).val()).toFixed(2));
});
It just takes the value, casts it to a float, renders it to a string to the number of decimal places, and puts it back in as the value.
I've had a little play around with this and looked at the spec. It says that it must be a valid floating point number. There's one sentence in the definition of a valid floating point number it gives which caught my attention:
The best representation of the number n as a floating point number is
the string obtained from applying the JavaScript operator ToString to
n.
This means that the format will always be consistent with assessing what the number is, then using JavaScript's toString on that number. So no trailing 0s then.
So, you're going to have to resort to JavaScript. This isn't straightforward because document.getElementById('numInput').value = '0.50'; still gets corrected to 0.5, so the validation isn't triggered at onchange where the default action can be prevented, it's triggered internally.
This is the best solution I could come up with... it's a bit of a hack, and will need a bit of tweaking for robustness, but hopefully it'll do what you want:
var numInput = document.getElementById('numInput');
numInput.addEventListener('keypress', function () {
this.setAttribute('type', 'text');
});
numInput.addEventListener('click', function () {
this.setAttribute('type', 'number');
});
So if the user wants to enter the number by typing, it switches the input type to text, but when they click it, it converts it back to a number.
If you always want the trailing 0s no matter what the user types, then you could do it something like this:
var numInput = document.getElementById('numInput');
numInput.addEventListener('blur', function () {
if (this.value === '') {
return;
}
this.setAttribute('type', 'text');
if (this.value.indexOf('.') === -1) {
this.value = this.value + '.00';
}
while (this.value.indexOf('.') > this.value.length - 3) {
this.value = this.value + '0';
}
});
numInput.addEventListener('focus', function () {
this.setAttribute('type', 'number');
});
Edit: I think the second solution is more inline with what the user might expect, but it means that if the user types 0.5 it will be coerced to 0.50, so it depends if that's what you want.