1
onchange="myfunction()"

The above works perfectly when I want the Javascript function "myfunction" to execute as soon as a user inputs some text into an input field however, I have a situation where the browser automatically inputs the text. How can I execute myfunction when the field is updated with the following:

document.getElementById("myfield").value = "my value"

"onchange" does not recognise DOM changes.

Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
cleverpaul
  • 935
  • 4
  • 12
  • 28
  • I have considered using setinterval to check the field however, I am not sure on how to do this. – cleverpaul Aug 26 '16 at 03:32
  • document.getElementById("myfield").value = "my value" – cleverpaul Aug 26 '16 at 03:33
  • Wait, your example isn't the browser updating the field, that's your own JS updating the field. Possible duplicate: http://stackoverflow.com/questions/7055729/onchange-event-not-fire-when-the-change-come-from-antoher-function. Regarding the browser updating the field, here's a possible duplicate: http://stackoverflow.com/questions/11708092/detecting-browser-autofill – nnnnnn Aug 26 '16 at 03:34
  • With jQuery: `$("#myfield").val("my value").change();` – nnnnnn Aug 26 '16 at 03:39
  • Just make a default value for the field, and periodically compare the value to the default using setInterval() to call document.getElementById("myfield").value; Any time they don't match, run your function and reset the variable that holds the default value to match what was last detected in the text field... or if you only want it to execute once, set a flag that shuts down that section of your script. while(someVariable === true) {setInterval. . . somewhere down the line after a successful check someVariable = false;} – Chris Aug 26 '16 at 03:44
  • Have you tried the oninput event instead of onchange? – Nekomajin42 Aug 26 '16 at 04:20

1 Answers1

3

onchange only fires when the user types into the input and then the input loses focus.

But you can trigger the event using:

$("#myfield").trigger("change");

$(function(){

 $('#btn').click(function(){
   document.getElementById('myField').value = "my value";
    $('#myField').trigger('change');
  });
  
})
function myfunction(){
   alert('Value Changed');
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type = "text" onChange = "myfunction()" id="myField"/>
<button id="btn">Change
</button>

onchange only fires when the user types into the input and then the input loses focus.

But you can trigger the event using:

$("#myfield").trigger("change");

JSFIDDLE

Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400