从输入类型number中获取无效值

Get invalid value from input type number

本文关键字:获取 无效 number 输入 类型      更新时间:2023-09-26

我使用的输入类型是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: ''}