2

When I change item in selectbox, a property of DOM seems changed. So I coded below:

<select id="hoge">
<option value="0">hoge</option>
<option value="1">piyo</option>
</select>

<script>
var hoge = document.getElementById("hoge").addEventListener("change", func, false);
document.getElementById("hoge").value = 1; // <- (1)

function func(e) {
alert("Detected!");
}
</script>

In this case, when I change item in selectbox, func is called. But when (1) is called, func is not called. Change event seems to detect only committed by the user.

So I tried MutationObserver.

<select id="hoge">
<option value="0">hoge</option>
<option value="1">piyo</option>
</select>

<script>
var hoge = new MutationObserver(function(mutations) {
alert("Detected!");
});
hoge.observe(document.getElementById("hoge"), { attributes: true, subtree: true });
document.getElementById("hoge").options[1].setAttribute("selected", "selected"); // <- (1)

</script>

In this case, when (1) is called, func is called. But when I change item in selectbox, func is not called. MutationObserver seems to detect only attributes.

I want to call func in either case. How to I detect change in a property of DOM by script?

couyoh
  • 313
  • 3
  • 9
  • Yes because it listens to only attribute changes – Arun P Johny Mar 04 '16 at 03:59
  • *I want to call func in either case* then attach listeners for both. The value of a select element is the value of the selected option (if there is one), setting it directly has no effect. The *change* event is intended for user interaction, not programmatic (e.g. originally "when the value is changed and the control loses focus"). – RobG Mar 04 '16 at 04:17

1 Answers1

0

I think there are 2 ways you can try:
1st is manually handle the on change event, without considering event bubble or propagation, then call onchange right after you change the value of element. Like this:

var myEle = document.getElementById("hoge");
myEle.value = 1; // <- (1)
myEle.onchange()

2nd is to make it naturally like browsers work, then try to create and dispatch event on that element. Like this:

if ("createEvent" in document) {
    var event = document.createEvent("HTMLEvents");
    event.initEvent("change", false, true);
    myEle.dispatchEvent(event);
} else
    myEle.fireEvent("onchange");
Đinh Hồng Châu
  • 5,300
  • 15
  • 53
  • 90
  • Or if you are familiar with jQuery, then can refer answer in [here](http://stackoverflow.com/questions/16781778/detecting-attribute-change-of-value-of-an-attribute-i-made) or [here](http://stackoverflow.com/questions/4561845/firing-event-on-dom-attribute-change) – Đinh Hồng Châu Mar 04 '16 at 04:31