0

I have an input form that is being dynamically updated with JavaScript. Using d3, I want to create an event listener that will run a function every time this input is manipulated.

Currently, it will run if I manually change the input field, but not if it is updated using the JavaScript. I have tried using .on("change",... and .on("input",....

Here is an example of the functionality I am trying to get:

<!DOCTYPE html>
<meta charset="utf-8">

<input value="0" id="input1">
<button  onclick="clickFunc();">Click Me</button>


<script src="http://d3js.org/d3.v3.min.js"></script>
<script>

d3.select("#input1").on("input", function() {
// not printing when updated by javascript
  console.log('value changed');
});

function clickFunc() {
    document.getElementById('input1').value = document.getElementById('input1').value + 1;
}

</script>
cacti5
  • 2,006
  • 2
  • 25
  • 33

2 Answers2

1

you can execute functions with the oninput="" attribute in an input element.

<input type="text" oninput="myFunction()">

In JS, you can also use:

$("myobject").oninput = function(){myScript};

or you are better with this one:

$("myobject").addEventListener("input", myScript);
Felix Haeberle
  • 1,530
  • 12
  • 19
0

You need to use MutationObserver window class to observe an input's change triggered by JS.

Keep in mind that simply setting input's node value property, for instance, won't trigger MutationObserver. You have to invoke setAttribute(value, "value") to get the change picked up by MutationObserver.

Here's a working example I've made: https://codepen.io/Inlesco/pen/rmxdpz

Of course, this is a vanilla JS solution. If you don't care about vanilla and using jQuery is a desirability, you can attempt to use this jQuery-fied answer: Detect all changes to a <input type="text"> (immediately) using JQuery

Though, I can't guarantee it'll work. Have not tested.

Community
  • 1
  • 1
Denialos
  • 956
  • 7
  • 16