This is strange behavior to me but on Webkit browsers (Chrome/Safari, not Firefox) if I include a space in a string of numbers in an <input type=number>
then the value
of that input is empty.
See this JSFiddle: http://jsfiddle.net/timrpeterson/CZZEX/5/
Here's the code:
<input id='withOutspace' type='number' value='123'>
<input id='with_space' type='number' value='123 123'>
<button>click</button>
$('button').click(function(){
alert("withOut:"+$('#withOutspace').val()+" |||| with:"+$('#with_space').val());
});
If you go to this JSFiddle, you'll notice that the with_space
input is empty. But if you put it in it a number that has a space or any non-numeric characters, the alert will say that input is empty.
Obviously, this is a disaster for form validation with credit card numbers, etc. so does anyone have a hack for this?
A way to control input number is to set it empty on blur when you can't read value
You can formatted it by the way, and if you have invalid char on server side you can send a bad request response.
If you want a requiered field, you can just check if the input is empty with javascript before your server call
It is not really the answer of the initial question but I was looking for a user friendly control for this type of input when I arrived here
The hack is to use
type="tel"
instead oftype="number"
.This solves the 2 main issues:
Please see this JSFiddle: http://jsfiddle.net/timrpeterson/CZZEX/6/
You're setting a numeric input field to a string which is not a number. What did you expect to happen? The whole point is that these fields don't allow or accept non-numeric input. They are documented as only accepting a floating point value.
There is no "hack" available or required; the solution is to stop using a
number
input field for a value that isn't a number. Credit cards, phone numbers, etc; these things are not numbers. They contain digits as a subset of the valid characters, but they also contain completely non-numeric characters like spaces, hyphens and parenthesis. They need to be stored and treated as regular strings.Use
<input type="text"/>
.My hack for this problem includes the following (i use jQuery validators):
Later in validator method i do this:
I can suggest two ways. 1. Prevent chars in input
or 2. Change input's type on fly
this allows to put whatever you want and change its type back
onblur
But still you cannot store nonnumerical values in input with type=number, so
val()
will always return you empty string if it meets char or space.So, at least you have to remove all garbage with
.replace(/[^\d]/g, '')
- that means "remove all except numbers" before you change type backIn my example I show both methods + clear input values.