2

Obviously, if I have a 'select' element, I can add an event listener for changes using some basic JS:

document.querySelector('select').addEventListener('change', function(ev){
  console.log('Changed', ev.target.value)
})

Click the 'select' element, modify the value, the log fires. Simple stuff.

However I'm working on a library for styled select boxes - like chosen or select2 without the jQuery dependency.

In my library, clicking the styled select box changes the .value of the real select box:

query('select').value = newValue;

I can see this is working if I make the real select box visible.

However, changing the value of the select box through JS doesn't trigger the select boxes 'change' event.

Is there a way I can change the select boxes value though JS and still have change events attached to the select box fire?

4

3 回答 3

1

Javascript

function fireEvent(element, event) {
    if (document.createEventObject) {
        // dispatch for IE
        var evt = document.createEventObject();
        return element.fireEvent('on' + event, evt)
    } else {
        // dispatch for firefox + others
        var evt = document.createEvent("HTMLEvents");
        evt.initEvent(event, true, true); // event type,bubbling,cancelable
        return !element.dispatchEvent(evt);
    }
}

document.querySelector('select').addEventListener('change', function (ev) {
    console.log('Changed', ev.target.value)
});

btn.onclick = function () {
    select.selectedIndex = 2;
    var obj = document.querySelector('select');
    fireEvent(obj, 'change');
}

用户调用

var yourPlugin=new CustomSelect(options);
yourPlugin.value("3");

插件功能

function value(val) {
    if (!val) return select.value;
    select.value = val;
    fireEvent(select, 'change');
}

演示

于 2014-09-22T12:15:55.403 回答
0

基于@Hamix 的出色回答,以及MDN 关于 createEvent() 已过时的一些建议,我最终选择了:

var changeEvent = new Event('change');
realSelect.dispatchEvent(changeEvent);

这是一个演示- 再次基于 @Hamix 的 jsfiddle 所以去给他一个赞成票。

于 2014-09-24T10:03:28.697 回答
0

只是一个想法:更改值后自己触发事件:

var el = query('select');
el.value = newValue;
el.dispatchEvent(new Event('change'));
于 2014-09-22T11:30:21.837 回答