pet*_*hel 10 html javascript html5 reactjs
我正在使用输入类型编号.如果无效,我如何从中获取值.例如,使用类型编号并打印"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>
Run Code Online (Sandbox Code Playgroud)
这实际上是可能的(至少在 Chrome 和 Edge 等基于 Chromium 的浏览器中),只是很痛苦。您可以通过选择界面获取:
const input = /*...the input...*/;
input.select();
const text = getSelection().toString();
Run Code Online (Sandbox Code Playgroud)
遗憾的是,Firefox 没有运气。
实例:
const input = /*...the input...*/;
input.select();
const text = getSelection().toString();
Run Code Online (Sandbox Code Playgroud)
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}"`);
});Run Code Online (Sandbox Code Playgroud)