0

I am searching for the way to trigger some JavaScript when input field is populated by code.

my field looks like this:

<input class="form-control" type="string" name="total" id="total" {% if object.total != None %} value="{{ object.total }}"{% endif %} oninput="onChange()" required>

In this case, if I type anything inside this field the method is triggered, but if I populate context object with content, this method is not called. (so the object.total is not empty, and the value is set: value=object.total)

How do I triggered method when value is populated like

value=object.total
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Marko Zadravec
  • 8,298
  • 10
  • 55
  • 97
  • You might need to add some javascript code to check the value of the input when the page loads and then trigger that function – art Jun 12 '18 at 13:54
  • so you mean something like : if value end if? – Marko Zadravec Jun 12 '18 at 14:09
  • Try `window.addEventListener('load', onChange);` along with some condition to check to ensure that the value is not empty. – art Jun 13 '18 at 07:32

1 Answers1

0

As far as I know it is by design that DOM changes triggered with code will not be caught by event listeners. However you can dispatch the onchange event yourself. (more info here How can I trigger an onchange event manually?).

So what you can do is wrap your logic in a custom function like this:

function changeInputValue(input, value) {
  // set the new value on the input first
  // then trigger the input onchange event manually
}
Halcyon
  • 611
  • 7
  • 7