如何在输入文本框上编程触发输入事件?

19

如您在下面的代码片段中所看到的,一旦单击其中一个按钮,字段中的文本会更改,但是事件不会触发(也不会运行alertTextInput()方法),当您直接在文本字段下键入文本时,预期的事件将被触发。

如何通过使用代码或使用更改文本并触发事���的方法手动激活事件?谢谢!

const changeTextButton = document.querySelector("#change-text");
const clearButton = document.querySelector("#clear");
const inputField = document.querySelector("#query");

changeTextButton.addEventListener("click", changeText);
clearButton.addEventListener("click", clear);
inputField.addEventListener("input", alertTextInput);

function changeText() {
  inputField.value = "Demo Text!!";
  inputField.dispatchEvent(new Event("input"))
}

function clear() {
  inputField.value = "";
  inputField.dispatchEvent(new Event("input"))
}

function alertTextInput() {
  alert(inputField.value);
}
<input type=text id="query">
<button id="change-text">Change the text programmatically</button>
<button id="clear">Clear</button>


1
你想要更改哪个文本?我很难理解你的问题。 - Abslen Char
我假设你是在问如何在通过 inputField.value = "Demo Text!!"; 更改文本后运行 alertTextInput() - 不幸的是,这不被认为是输入事件监听器的事件。我认为你需要手动调用它。 - adprocas
可能重复:https://dev59.com/oGQo5IYBdhLWcg3wfPbK检测文本输入框的编程式更改。 - Sebastian Speitel
这是另一个重复内容 - https://dev59.com/xlgQ5IYBdhLWcg3wqFkF - adprocas
欢迎查看下面的答案,从我的印象来看,这个问题并不是从上面附加的链接中复制的。 - Sagi Nadav
3个回答

37

13

来自 React 文档

React 期望监听到 input 事件

所以在设置值后触发 input 事件。 这里是如何触发的

最终代码如下:

var event = new Event('input', {
    'bubbles': true,
    'cancelable': true
});

inputElement.value = '0.2'
inputElement.dispatchEvent(event);

1
如果我理解正确,您希望在单击“更改”按钮时更改输入文本并出现警报。由于changeText()函数只会更改文本,您不应该期望出现警报。
您可以将alertTextInput()函数添加到changeText()函数的底部。
function changeText() {
  inputField.value = "Demo Text!!";
  alertTextInput();
}

我更喜欢基于事件的解决方案。 - Sagi Nadav
我遇到了与楼主类似的情况,发现这个答案对我很有用。我尝试使用dispatchEvent("input")和addEventListener("input", myfunc)配对,但由于某些原因它没有起作用。我喜欢你的简单解决方案。所以谢谢。 - calabash

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接