Programmatically manipulating DOM element value doesn't fire onchange event

孤人 提交于 2019-12-31 05:45:09

问题


I've got a hidden form field, and when a button gets pressed the value of the hidden field is changed. Now, I've added an observer to the hidden field, listening for changes to occur. For some reason, though, the event listener never kicks in, even though the value of the hidden element changes. I'm using Prototype and Firefox 3.6.

The code looks roughly like this:

button.observe('click', function(event) {
  hiddenField.setValue(someValue);
});

hiddenField.observe('change', function(event) {
  alert('It works!');
});

Does anyone have a clue why the latter observer doesn't execute?

Thanks!


回答1:


You need event.simulate.js

Fire the event..

button.observe('click', function(event) {
  hiddenField.setValue(someValue);
  hiddenField.simulate('change');
});

And then observe it:

hiddenField.observe('change', function(event) {
  alert('It works!');
});



回答2:


I don't think input elements that are hidden respond to that event.

I don't know prototype, but I think the events being triggered is entirely up to the browser.

Here is an example with jQuery on JSbin. Notice that changing the text yourself fires the event, however the next part of code that changes the value via script does not fire it.



来源:https://stackoverflow.com/questions/2842266/programmatically-manipulating-dom-element-value-doesnt-fire-onchange-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!