4

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: IE result FF: FF result

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.

Michael Laffargue
  • 10,116
  • 6
  • 42
  • 76

2 Answers2

4

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 );
});
Pablo Lozano
  • 10,122
  • 2
  • 38
  • 59
1

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/

Yuriy Galanter
  • 38,833
  • 15
  • 69
  • 136
  • Thanks I'll test it in GWT and validate the answer. Don't you think the `add` should work by default ? – Michael Laffargue Mar 06 '14 at 17:00
  • I think it should. I guess Microsoft interprets this differently and by "add" meaning adding to the last group – Yuriy Galanter Mar 06 '14 at 17:02
  • I finally went with Pablo answers as I don't have to take care if an optgroup is present or not. But obviously your answer is correct too. Thanks a lot – Michael Laffargue Mar 06 '14 at 17:10
  • No prob. Yes his answer is more streamlined. Btw, since you're already using jQuery, you can ditch getElementById/createElement/appendChild in favour of jQuery methods. – Yuriy Galanter Mar 06 '14 at 17:11