Environment:
Only JavaScript (no jquery :( )
Button click event handler is not available for change.
Is there a way to listen to textbox if its value is changed programmatically?
<input type="button" id="button1" value="button" />
<input type="text" id="text1" />
var btn1 = document.getElementById('button1');
var txt1 = document.getElementById('text1');
btn1.onclick=function(){ txt1.value = 'hello world'}
https://jsfiddle.net/yrt7e57w/
You can use element.dispatchEvent(event)
when you change the text programmatically. In your example it would look like:
var btn1 = document.getElementById('button1');
var txt1 = document.getElementById('text1');
btn1.addEventListener("click", function() { // Add to OnClick of button.
txt1.dispatchEvent(new Event('change')); // force change event to run on textbox.
});
txt1.addEventListener("change", function(e){ // EventListener for OnChange of the element.
alert("changed");
});
Just the addEventListener
on its own will not work as it isn't exactly being changed in the DOM.
Above is a simple solution which requires a few key presses but for a much more maintainable and reusable solution, check out Snowmonkey's answer (and probably most other answers to this question), https://stackoverflow.com/a/44708746/640263.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With