JavaScript – Custom Selectbox Trigger Onchange Event Multiple Times

ce-1.7.0.2javascriptprototype-js

We have implemented a jQuery selectbox plugin and created a custom trigger event to get the data when a selectbox is changed. For example, we use this to select the desired product attribute options.

Everything goes well until we select an option which has already triggered in the same 'session'. Then nothing happens. How is that possible?

The trigger event:

Element.prototype.triggerEvent = function(eventName)
{
    if (document.createEvent)
    {
        var evt = document.createEvent('HTMLEvents');
        evt.initEvent(eventName, true, true);

        return this.dispatchEvent(evt);
    }

    if (this.fireEvent)
        return this.fireEvent('on' + eventName);
}

var global_select = '';

function customEvent(id, event) {
    global_select = id;
    $(id).triggerEvent(event);
    global_select = '';
}

The jQuery code:

jQuery('select').change(function(e) { 
    id = jQuery(this).attr('id');
    if (id && id != global_select)
        customEvent(jQuery(this).attr('id'), 'change');

    jQuery('select').each(function() {
        var id = jQuery(this).attr('id');
        if (jQuery(this).css('display') == 'none') {
            jQuery(this).selectbox('detach');
            jQuery(this).hide();
        } else {
            jQuery(this).selectbox('attach');
        }
    });
});

jQuery('select').each(function(){
    if (jQuery(this).css('display') != 'none') {
        jQuery(this).selectbox();
    }
});

Best Answer

We fixed this by changing the jQuery version from 1.10.2 to 1.8.2.