Onchange in Firefox is triggered without changing

我是研究僧i 提交于 2019-12-01 00:03:00
Shadow

This is certainly a bug in Firefox that assign the selected value and selected index upon hovering the items, when there is no selected index defined.

While I can't fix the bug, one workaround that is pretty simple and working is adding empty and hidden item to the list to be the first item and assigning it as the selected item.

For example:

<select id="mySelect">
    <option value="" style="display: none;"></option>
    <option value="1">first</option>
    <option value="2">second</option>
</select>

The user won't see any change and when you "clear" the selection, assign selected index of 0 instead of -1 e.g.

var oDDL = document.getElementById("mySelect");
oDDL.selectedIndex = 0;

Live test case - behaves properly even on Firefox now.

Update - The above code is not working properly in IE8 as it still showing the first empty option. To solve this, it's possible to simply remove the option in all browsers that support it when the browser is not Firefox. Updated code will be:

navigator.sayswho = (function(){
    var N = navigator.appName, ua= navigator.userAgent, tem;
    var M = ua.match(/(opera|chrome|safari|firefox|msie)\/?\s*(\.?\d+(\.\d+)*)/i);
    if (M && (tem = ua.match(/version\/([\.\d]+)/i)) != null) M[2] = tem[1];
    M = M? [M[1], M[2]]: [N, navigator.appVersion, '-?'];
    return M;
})();

window.onload = function() {
    var oDDL = document.getElementById("mySelect");
    oDDL.selectedIndex = 0;
    var blnFirefox = (navigator.sayswho[0].toLowerCase().indexOf("firefox") >= 0);
    if (!blnFirefox && oDDL.remove) {
        oDDL.remove(0);
        oDDL.selectedIndex = -1;
    }
    oDDL.onchange = function() {
        alert("hello");
    };
};

The function that identifies the browser was taken from this answer.

Updated fiddle - working in Firefox, Chrome, IE9 and IE8.

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