从输入类型number中获取无效值
Get invalid value from input type number
我使用的输入类型是number。我怎么能得到这个值,当它无效。例如,使用type number并只打印'e',这本身是无效的。
我正在使用React,但我认为这个问题非常普遍。
onChange(event) {
console.log(event.target.value) //is empty string when not using number
}
<form novalidate>
<input type="number" onChange={this.onChange}>
</form>
这实际上是可能的(至少在Chrome和Edge等基于Chrome的浏览器中),这只是一个痛苦。你可以通过选择界面获得它:
const input = /*...the input...*/;
input.select();
const text = getSelection().toString();
遗憾的是,火狐的运气不佳。
生活的例子:
const theInput = document.getElementById("the-input");
const theButton = document.getElementById("the-btn");
function saveSelection() {
const selection = getSelection();
const range = selection.rangeCount === 0 ? null : selection.getRangeAt(0);
return range;
}
function restoreSelection(range) {
const selection = getSelection();
selection.removeAllRanges();
selection.addRange(range);
}
function getRawText(input) {
const sel = saveSelection();
input.select();
const text = getSelection().toString();
restoreSelection(sel);
return text;
}
theButton.addEventListener("click", event => {
const value = theInput.value;
const text = getRawText(theInput);
console.log(`value = "${value}", but text = "${text}"`);
});
<p>
Copy some invalid numeric text (like <code>9-9</code>) and paste it into this field:
</p>
<input type="number" id="the-input">
<p>
Then click here: <input type="button" id="the-btn" value="Go">
</p>
根据我的发现,这个特定的问题没有解决方案。
获得它的唯一方法是将input
设置为type="text"
,并在函数内决定有效性:
(来源:在JavaScript中验证十进制数字- IsNumeric())
function onChange(event) {
if(!isNaN(parseFloat(event.value)) && isFinite(event.value)){
console.log("It's numeric: " + event.value);
}
else {
console.log("It's not numeric: " + event.value);
}
}
<input type="text" onChange="onChange(this)">
你必须以这种方式调用onChange JS函数onChange="onChange(this)"
和使用事件。值代替event.target.value
,以便得到正确的结果。
function onChange(event) {
console.log(event.value)
}
<form novalidate>
<input type="number" onChange="onChange(this)">
</form>
我不太明白你的意思,但我想你是在寻找输入值。您正在寻找目标value
,但您的标签没有此属性。在本例中,您需要将value ={this.state.value}
作为道具添加到输入标记中,并在构造函数中添加新状态。this.state = {value: ''}
相关文章:
- 获取所选选项的Javascript在Webkit/FF中有效,但在IE中无效
- TypeError: 使用 Jquery JSON 获取数据时无效的 'in' 操作数 obj
- 无效的“in”操作数 obj JQUERY - 尝试从 JSON 获取数据时出现类型错误
- 相位器.js获取给定的无效相位器状态对象
- PHP 和 RegEx:在 XML 标记之间获取原始数据,即使整个 XML 似乎无效
- Getting TypeError:无效'在'使用ajax获取数据时的操作数obj
- 如何获取XML文件中节点的值.代码无效
- ReactFire-获取'对象作为React子对象无效'将Firebase绑定到React状态时
- 获取输入框的值无效
- 从输入类型number中获取无效值
- 获取'无效的返回语句'我也不知道为什么
- 获取“websocket连接无效”;使用套接字出错.ec2实例上的IO
- 如何获取无效输入的内容长度
- 通过id获取元素无效
- D3指令-获取路径无效值的错误
- 使用jQuery在大括号中获取无效的HTML代码
- 带有浏览器.js的 Babel,获取未捕获的语法错误:正则表达式无效
- 获取访问令牌时,签名LinkedIn Oauth无效
- 从选择框中获取选定值无效
- Jquery ajax发送数据并获取:SQLSTATE[HY093]:无效的参数编号