jQuery val拒绝从数字字段返回非数字输入(在Chrome下) [英] jQuery val refuses to return non numeric input from a number field (Under Chrome)

查看:125
本文介绍了jQuery val拒绝从数字字段返回非数字输入(在Chrome下)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 在jQuery中偶然发现了一些奇怪的东西,同时编写了一些验证代码 - 我有一个html5number字段; < input type =numberclass =required numeric/> 

然后,我的脚本将查看页面上的每个字段,检查类并根据需要进行验证。我奇怪地注意到,如果我在我的一个数字字段中输入'X',我会得到一个请在此字段中输入值错误,而不是这应该是数字错误。经过一些头部划伤和大量调试之后,我敲了一个jsFiddle来演示我的理论 - 看起来如果你在一个数字字段中输入一个字符,然后尝试从jquery中做一个.val(),它将不会返回任何东西 - 就像字段是空的(我在Chrome浏览器中遇到过这种情况 - 不确定它是否在所有浏览器中都是这样);

http://jsfiddle.net/shawson/SE46L/3/



这里是小提琴输入一些数字,然后几个字母看到疯狂。任何人都知道这是否是设计,如果是这样的话......为什么? 解决方案

这不是jQuery问题。如果使用本地element.value(例如getElementByID('something')。value),则会得到相同的结果。 Chrome浏览器如何处理输入类型=数字,你可以选择使用type = text和pattern属性来解决它。 这个旧的问题更多的背景。


Just stumbled across something weird in jQuery, while writing some validation code- I have an html5 "number" field;

<input type="number" class="required numeric" />

My script will then look at every field on the page checking out the classes and validating as needed. I noticed weirdly that if i enter an 'X' into one of my numeric fields i get a "Please enter a value into this field" error instead of a "this should be a number" error. After some head scratching and a lot of debugging I knocked up a jsFiddle to demo my theory- it appears if you enter a character into a number field, then try to do a .val() from jquery it will return nothing- as though the field was empty (I came across this in Chrome- not sure if it works like this across all the browsers);

http://jsfiddle.net/shawson/SE46L/3/

Here's the fiddle- enter some numbers, then a few letters to see the crazyness. Anyone know if this is by design, and if so... why?

解决方案

This is not a jQuery issue. You will get the same result if you use the native element.value (e.g. with getElementByID('something').value). It's quirk of how Chrome deals with input type=number and you can choose to work around it by using type=text and the pattern property.

See this older question for more background.

这篇关于jQuery val拒绝从数字字段返回非数字输入(在Chrome下)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆