SELECT box: On IE item is added to OptGroup instead of root. FF ok

社会主义新天地 提交于 2020-02-02 04:24:12

问题


I've got a behaviour a bit strange with Select Box and OptGroup: I use OptGroup and try to add at the end a single item which I expect to be out of the OptGroup. FF does it as expected but IE adds it to the OptGroup

With this code : fiddle (Note: JQuery was just use for the .ready method, I can't use it in my project)

<select id="selectbox">
    <optgroup label="optGroup1">
        <option>aaaa</option>
    </optgroup>
</select>

$(document).ready(function() {
    var select = document.getElementById("selectbox");
    option = document.createElement( 'option' );
    option.value = option.text = "test";
    select.add( option );
});

The result is different in IE and FF

IE:

FF:

Note : I'm using Javascript to add the item because I'm currently using GWT. So this is the way GWT adds an item to a select.


回答1:


This works in IE and Chrome, so it should work in FF:

$(document).ready(function() {
var select = document.getElementById("selectbox");
option = document.createElement( 'option' );
option.value = option.text = "test";
select.appendChild( option );
});



回答2:


You can actually insert the option after option group:

HTML (added ID for the Option Group)

<select id="selectbox">
    <optgroup label="optGroup1" id="optGroup1">
        <option>aaaa</option>
    </optgroup>
</select>

JavaScript

var optgroup1 = document.getElementById("optGroup1");
option = document.createElement( 'option' );
option.value = option.text = "test";

//insterting "after"
optgroup1.parentNode.insertBefore(option, optgroup1.nextSibling)

Demo: http://jsfiddle.net/tZ8sz/1/



来源:https://stackoverflow.com/questions/22221289/select-box-on-ie-item-is-added-to-optgroup-instead-of-root-ff-ok

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