Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to listen to textbox when its value is changed programmatically

Tags:

javascript

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/

like image 838
Rod Avatar asked Jun 22 '17 20:06

Rod


1 Answers

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.

like image 189
Peter Dempsey Avatar answered Sep 18 '22 11:09

Peter Dempsey