入力タイプ番号から無効な値を取得する 質問する

入力タイプ番号から無効な値を取得する 質問する

入力タイプ番号を使用しています。有効でない場合、この値を取得するにはどうすればよいでしょうか。たとえば、タイプ番号を使用して、それだけでは有効ではない「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>

ベストアンサー1

これは実際に可能です (少なくとも Chrome や Edge のような Chromium ベースのブラウザでは) が、面倒なだけです。選択インターフェースから取得できます:

const input = /*...the input...*/;
input.select();
const text = getSelection().toString();

残念ながら、Firefox では運がありませんでした。

実際の例:

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>

おすすめ記事