获取< input type =" number">的值使用JS时,它包含非数字字符 [英] Get value of <input type="number"> with JS when it contains non-numeric characters

查看:137
本文介绍了获取< input type =" number">的值使用JS时,它包含非数字字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此jsfiddle演示了以下问题。

最简单的例子是:

<input id="number" type="number" value="1">
console.log(document.getElementById('number').value);

按预期记录1。但是:

<input id="number" type="number" value="1A">
console.log(document.getElementById('number').value);

只记录空字符串'',因为值中包含非数字字符。某些设备+浏览器(例如Chrome)允许您在这些输入中输入非数字字符。

Just logs an empty string '', because of the non-numeric character in the value. Some devices+browsers (e.g. Chrome) allow you to enter non-numeric characters in these inputs.

这很烦人,因为我想要设备的type =number输入支持它(例如iPhone,iPad数字键盘)。但是我想使用javascript来阻止输入脏输入 - 这需要获取keyup上的值 - 然后正则表达式替换非数字字符。

This is annoying because I want the type="number" input for devices that support it (e.g. iPhone, iPad number keyboard). However I want to use javascript to stop dirty input from being entered - which requires fetching the value on keyup - then regex replacing the non-numeric chars.

它似乎是jQuery的。 val()方法给出了相同的结果。

It appears jQuery's .val() method gives the same result.

推荐答案

这就是我要找的:

$('input[type=number]').keypress(function(e) {
  if (!String.fromCharCode(e.keyCode).match(/[0-9\.]/)) {
    return false;
  }
});

我知道防止用户输入可能很烦人,这仍然允许无效输入,例如 1.2.3

I understand preventing user input can be annoying and this still allows invalid input such as 1.2.3

然而在这种情况下,这正是我所需要的。希望它对其他人有用。感谢@ int32_t的建议。

However in this situation it is exactly what I needed. Hopefully it will be of use to someone else. Thanks to @int32_t for the suggestion.

这篇关于获取&lt; input type =&quot; number&quot;&gt;的值使用JS时,它包含非数字字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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