Detect change, if input-text is changed by JavaScript

天大地大妈咪最大 提交于 2019-12-13 03:13:41

问题


Summary- I am working on a text-comparison tool. I have two functions - an excel-parser, which fetches data from excel file and changes the input-text dynamically/programmatically.
- a text comparison function listens for any changes in the input field and runs text-comparison logic.

I am new to jQuery but have tried JS with eventListeners, oninput, onchange, onpaste, etc. Note: The following code snippet explains the situation. However, there is no such button click.

var a = document.getElementById("test");

function assignValue() {
  a.value = "Hello World";
}
a.addEventListener('input', recInput);

function recInput() {
  console.log("Sucess!");
}
<input id="test">
<button onclick="assignValue()">Click to add text</button>

Is there any way of capturing changes using JS? If not, I am open to using jQuery.


回答1:


You can use the MutationObserver API to do this.

Register a callback function that will deal with the changing attribute.

const input = document.getElementById('name');
const observer = new MutationObserver(list => {
  console.log("New Value: ", list[0].target.value);
})
observer.observe(input, {
  attributes: true,
  childList: false,
  subtree: false
});

function changeIt() {
  const randomString = Math.random() >= 0.5 ? "one" : "two";
  input.setAttribute("value", randomString);
  input.value = randomString;
}
<input placeholder="Enter some text" name="name" id="name" />
<button onclick='changeIt()'>Push me
</button>

You'll need to use setAttribute() and you'll need to set the Input element's value property to keep it in sync with the attribute. (as seen in the changeIt() function.




回答2:


You can use onkeydown for this.

var a = document.getElementById("test");

a.addEventListener('onkeydown', recInput);

function recInput(e) {
  console.log("Sucess!", e.key);
}


来源:https://stackoverflow.com/questions/56159513/detect-change-if-input-text-is-changed-by-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!