Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
387 views
in Technique[技术] by (71.8m points)

javascript - HTML5 input type=number value is empty in Webkit if has spaces or non-numeric characters?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The hack is to use type="tel" instead of type="number".

This solves the 2 main issues:

  1. It pulls up a number keypad on mobile devices
  2. It validates (and is not empty) with numbers or non-numbers as input.

Please see this JSFiddle: http://jsfiddle.net/timrpeterson/CZZEX/6/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...