javascript - 如何获取 <input type ="number"> 字段的原始值?

标签 javascript html validation input

我如何获得<input type="number">“真实”值领域?

<小时/>

我有一个input框,我正在使用较新的 HTML5 输入类型 number :

<input id="edQuantity" type="number">

Chrome 29 主要支持此功能:

enter image description here

我现在需要的是能够读取用户在输入框中输入的“原始”值。如果用户输入了数字:

enter image description here

然后edQuantity.value = 4 ,一切都很好。

但是如果用户输入无效文本,我想将输入框设置为红色:

enter image description here

不幸的是,对于 type="number"输入框,如果文本框中的值不是数字则 value返回一个空字符串:

edQuantity.value = "" (String);

(至少在 Chrome 29 中)

我如何获得<input type="number">“原始”值控制?

我尝试查看 Chrome 的输入框其他属性列表:

enter image description here

我没有看到任何类似于实际输入的内容。

我也无法找到一种方法来判断该框是否“为空”。也许我可以推断:

value          isEmpty        Conclusion
=============  =============  ================
"4"            false          valid number
""             true           empty box; not a problem
""             false          invalid text; color it red

注意:您可以忽略水平线之后的所有内容;这只是为了证明这个问题的合理性的填充物。另外:不要将示例与问题混淆。人们可能出于其他原因想要得到这个问题的答案,而不是将框涂成红色(一个示例:在 onBlur 事件期间将文本 "four" 转换为拉丁语 "4" 符号)

我如何获得<input type="number">“原始”值控制?

奖励阅读

最佳答案

根据WHATWG ,除非它是有效的数字输入,否则您应该无法获取该值。输入数字字段的清理算法表示,如果输入不是有效的 float ,则浏览器应该将该值设置为空字符串。

The value sanitization algorithm is as follows: If the value of the element is not a valid floating-point number, then set it to the empty string instead.

通过指定类型 ( <input type="number"> ),您要求浏览器为您做一些工作。另一方面,如果您希望能够捕获非数字输入并对其执行某些操作,则必须依赖旧的经过尝试的真实文本输入字段并自行解析内容。 p>

W3也具有相同的规范并添加:

User agents must not allow the user to set the value to a non-empty string that is not a valid floating-point number.

关于javascript - 如何获取 &lt;input type ="number"> 字段的原始值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26751359/

相关文章:

javascript - 将Class添加到具有特定属性的div

php - 在 PHP 文件中包含外部样式表

Java - 在特殊情况下关闭类字段的 Spring 验证

javascript - 根据屏幕大小调整 html 表格宽度

javascript - @ngrx/store 与 Angular 2 : Cannot read property of undefined

javascript - 未捕获的类型错误 : Cannot read property '0' of undefined in select box

jQuery - Validate() 并对相似的表单项进行分组

javascript - 为什么我不能在 jQuery 中解析 A​​jax html GET 响应?

php - PHP邮件功能无法完成电子邮件的发送

C# 验证 : IDataErrorInfo without hard-coded strings of property name?