InnerHTML and Select option in IE

Hello. This is my second post.

The non-DOM property innerHTML can't add options to a tag select in Internet Explorer.

Example not working:

document.getElementById("my_select").innerHTML = "<option value='1'>not</option> <option value='2'>work</option>"; 

The correct way to insert options in a select is using appendChild or addOption functions. But that's tiring if we are working with Ajax.

Use innerHTML is not the standard but it is very useful.

The function above, will help you to insert options like using innerHTML, in IE, Firefox or Opera.

Updated: now supports option-selected

Using my function:

var inner = "<option value='1'>Now</option> <option value='2'>work</option>"; 
select_innerHTML(document.getElementById("my_select"),inner);

The function. Add to your lib.

function select_innerHTML(objeto,innerHTML){
/******
* select_innerHTML - corrige o bug do InnerHTML em selects no IE
* Veja o problema em: http://support.microsoft.com/default.aspx?scid=kb;en-us;276228
* Versão: 2.1 - 04/09/2007
* Autor: Micox - Náiron José C. Guimarães - micoxjcg@yahoo.com.br
* @objeto(tipo HTMLobject): o select a ser alterado
* @innerHTML(tipo string): o novo valor do innerHTML
*******/
    objeto.innerHTML = ""
    var selTemp = document.createElement("micoxselect")
    var opt;
    selTemp.id="micoxselect1"
    document.body.appendChild(selTemp)
    selTemp = document.getElementById("micoxselect1")
    selTemp.style.display="none"
    if(innerHTML.toLowerCase().indexOf("<option")<0){//se não é option eu converto
        innerHTML = "<option>" + innerHTML + "</option>"
    }
    innerHTML = innerHTML.toLowerCase().replace(/<option/g,"<span").replace(/<\/option/g,"</span")
    selTemp.innerHTML = innerHTML
      
    
    for(var i=0;i<selTemp.childNodes.length;i++){
  var spantemp = selTemp.childNodes[i];
  
        if(spantemp.tagName){     
            opt = document.createElement("OPTION")
    
   if(document.all){ //IE
    objeto.add(opt)
   }else{
    objeto.appendChild(opt)
   }       
    
   //getting attributes
   for(var j=0; j<spantemp.attributes.length ; j++){
    var attrName = spantemp.attributes[j].nodeName;
    var attrVal = spantemp.attributes[j].nodeValue;
    if(attrVal){
     try{
      opt.setAttribute(attrName,attrVal);
      opt.setAttributeNode(spantemp.attributes[j].cloneNode(true));
     }catch(e){}
    }
   }
   //getting styles
   if(spantemp.style){
    for(var y in spantemp.style){
     try{opt.style[y] = spantemp.style[y];}catch(e){}
    }
   }
   //value and text
   opt.value = spantemp.getAttribute("value")
   opt.text = spantemp.innerHTML
   //IE
   opt.selected = spantemp.getAttribute('selected');
   opt.className = spantemp.className;
  } 
 }    
 document.body.removeChild(selTemp)
 selTemp = null
}

Another solution to innerHTML/Select/IE problem, here

Portuguese original version.

80 comments:

  1. I found your site via Google trying to fix the IE select bug. Thanks for posting that function, works a treat.

    Interesting to note that Internet Explorer has known about the bug scince 2003, yet the problem still exists in IE7. Amazing that they are still making that browser.

    ReplyDelete
  2. Another bad way of adding is

    var selText = "(OPTION)(/OPTION)..... //Options as HTML
    First

    MySelects.innerHTML="";
    MySelects.outerHTML= MySelects.outerHTML.replace("(/SELECT)",selText + "(/SELECT)");

    ReplyDelete
  3. it's 3:15 AM - you rock. I've been bashing my head against the keyboard for hours. Thanks!

    ReplyDelete
  4. Fine and usefull solution, many thanks to you. Maybe you also had an idea about selecting an value at the option-list?
    Tried this one:
    [code]
    for (var e=1;e<=daysThisMonth;e++)
    showDays += "<option value=\""+ e+ "\"";
    if (e==thisDay) {
    showDays += "selected=\"selected\" ";
    }
    showDays += ">"+ e+ "<\/option>";
    }
    [/code]
    But the slection does not works with your script :(

    ReplyDelete
  5. Hey last anonymous,
    You dont need put a extra-bar ( \ ) before close the tag option.
    You can use just like this: "< / option>" (without space).

    I believe that will resolve your problem.

    If you have another problems with this, send-me a email.

    ReplyDelete
  6. Thanks very much. Worked on this all day today at work. MSDN solutions didn't work for me. This did.

    ReplyDelete
  7. Thanks for the nice post!

    ReplyDelete
  8. Thanks!!! The function works great in IE

    ReplyDelete
  9. You're a lifesaver! I've been breaking my head on a piece of AJAX I wrote that worked perfectly in every browser except IE7 and your script did the trick! Thanks man!

    Pjotr from The Netherlands...

    ReplyDelete
  10. Your script seem to solve a problem I have been battling with for quite some time now.

    Thanks.

    But I cant figure out how to use. Do use as it is or have to make changes to it? If the later, what changes?

    Your assistance will very much be appreciated.

    ReplyDelete
  11. Sorry anonymous. I forget to explain how to use my script.
    Now i'll update this post and show to use.

    Thanks!

    ReplyDelete
  12. I now get it.

    Thanks for the timely update.

    ReplyDelete
  13. I've got large box loading from AJAX about 1000 items. On IE6 this code is then very slowly.
    Do you see some way to expand speed?

    ReplyDelete
  14. Hi Aleksander.
    Try to use the 'outerHTML' for IE.
    A anonymous write about this in my second comment.

    ReplyDelete
  15. Thanks for that,
    But I still have a problem with:
    field.childNodes.length
    it is 0?!

    ReplyDelete
  16. Hi Aleksander.

    NO, field.childNodes.length will be '0' just if you dont have options. Check your function.

    //You are using the outerHTML for IE and my function for FF?

    ReplyDelete
  17. Yes, I found your function is useful but problem exists in IE with lot of items.
    Then I try with outerHTML way and I can't set selected item.
    Can we speed up your function?

    ReplyDelete
  18. Hi Aleksander

    Send your code to my email (naironjcg A gmail.com). I will try to solve.
    But, I think that its not possible to be more fast that outerHTML.

    ReplyDelete
  19. Hello,

    thx for this great function, its work very nice!

    ReplyDelete
  20. Thanks Micox-Náiron J. C. G.
    Your script is good I've apply it successful

    ReplyDelete
  21. You can use outerHTML to fill the select then use script to select the correct option. It's still faster than using innerHTML.

    for(var i=0; i<my_select.options.length; i++)
    {
    if (my_select.options[i].value == "select_me")
    my_select.options[i].selected = true;
    }

    ReplyDelete
  22. is this work for IE7?

    ReplyDelete
  23. (Volo Mike says...)

    This was a lifesaver. Thanks so much for working this out. IE is such a pathetic browser that it's not even funny.

    Too bad you don't have Google AdSense ads on this blog -- I would have clicked on all your ads to give you some cash as a form of "thank you".

    ReplyDelete
  24. this is grt...did the job for me...Grt work!!

    ReplyDelete
  25. If you have a lot of information to display in the select... it's faster to do it like that...

    object=document.getElementById('ElementId');

    if(object!=null){


    var inner = "(option value='test1')display1(/option)";

    object.innerHTML=inner;
    object.outerHTML=object.outerHTML;

    }

    ReplyDelete
  26. Hi anonymous.
    I tried with outerHTML but it have problems when i see the result innerHTML in future.
    outerHTML just currectly work visually.

    Thanks for suggest.

    ReplyDelete
  27. Hi Micox - Náiron J. C. G.!

    Thanks for the post, because it's what I need...but it's not working at the moment on my code, there is probably a good reason!!!
    Could you help me??? I become crasy!!!
    Thanks.
    Solen

    ReplyDelete
  28. Yeah Solen, post your link of the problem.
    Thanks.

    ReplyDelete
  29. Great,

    This was a lifesaver to me !

    ReplyDelete
  30. Hey Micox,

    I've read through this site and I think it's exactly what I need. I've been reading about this problem and trying to resolve it for about 3 days now but with no luck, even with the Microsoft solutions. I'm not quite sure what parameters I send your function.

    I have a string of options:

    < option>Option 1< /option>
    < option>Option 2< /option>
    < option>Option 3< /option>

    that need to be put into the innerHTML of a < select>< /select>

    ReplyDelete
  31. a-HA!

    Figured it out, thanks again Micox. Three days of wanting to break my monitor over the shortcomings of MSIE have been brought to an end.

    ReplyDelete
  32. This isn't the first time your code has saved me.

    Thanks!

    ReplyDelete
  33. function select_innerHTML(select, inner) {
    select.outerHTML = select.outerHTML.substring(0, select.outerHTML.indexOf(')', 0) + 1) + inner + '(/select)';
    }

    The same. Shorter.

    Change '(' and ')' with properly rotated '^' ;)

    ReplyDelete
  34. I never write comments to stuff i find, but you just made my day. Many thanks and a beer for you mate!

    ReplyDelete
  35. great fix!

    finally a solution for that crappy IE bug

    PS. Use open standards, use Firefox

    ReplyDelete
  36. obrigado !!!
    you were very helpful !!!!

    ReplyDelete
  37. Thanks, this topic solved my problem.

    ReplyDelete
  38. vejam: http://support.microsoft.com/kb/276228
    Esse IE é sem comentários, fala como fazer a gambiarra mas não arrumam o bug...
    em vez de dar o innerHTML nos option apenas dê um innerHTML montando um novo select

    ReplyDelete
  39. IE fails to rebuild its DOM tree after you paste such an option string into a select element. Try calling "firstChild" or anything related to invoke IE DOM manipulation. Things would be OK after that.

    ReplyDelete
  40. hey bro... the srcipt do its work very well, thnx

    but... my options are ordered by an optgroup tag...

    how can i fix the problem????

    ReplyDelete
  41. You can also do it like this - rewrite the whole select: let's say that you have

    <select id="sel1">...</select> and you want to insert a string with option elements. Just place a <span id="span1"></span> pair around the <select> and have document.getElementById('sel1').innerHTML = "<select id='sel1'>..</select>"

    ReplyDelete
  42. I meant document.getElementById('span1').innerHTML
    above, in my previous comment

    ReplyDelete
  43. This comment has been removed by the author.

    ReplyDelete
  44. Thanks buddy this is better solution than solution provided by Microsoft website

    ReplyDelete
  45. I see the long line of people who have been spared the paid because of your effors. I just wanted to add my thank you note.

    ReplyDelete
  46. This seems to convert everything to lower case including the option values. I do a the call to 'toLowerCase'. Why is it necessary to covert the whole thing to lower case?

    ReplyDelete
  47. didn't work for me,here is my scenario:

    i send a request through ajax to a php page, get the OPTION's in the response and then set the innerHTML to the response, it works wtih FF but NOT IE, i tried your function and the probelm is still there,,,IE IS NOT WORKING,,,,but on FF it works fine

    ReplyDelete
  48. Se podria usar esta función para cambiar dinamicamente el select con AJAX?

    Alguna ayuda?

    ReplyDelete
  49. Si Raul, vea esto: http://www.webly.com.br/Micox/ajaxGo.htm

    ReplyDelete
  50. Bravo, super script! ;)

    ReplyDelete
  51. awesome great one
    good job ya man
    it's working :-)

    ReplyDelete
  52. Hi,
    really great stuff yar.......

    ReplyDelete
  53. Thank you!!! This problem was driving me insane!!! f***** IE!!

    ReplyDelete
  54. I love you!!!!!!! This solution rocks!!

    ReplyDelete
  55. Ran into the same problem using Ajax to filter dropdown based on first dropdown choice in IE.

    Easy fix:

    http://support.microsoft.com/kb/276228

    ReplyDelete
  56. Thank you for your usefull function, it saved me a lot of time.
    I have just removed the toLowerCase() because it was lowering the case in my option values as well.
    I understand that this was for finding both option and OPTION but I will pay attention in my code.

    Gianni Bragante

    ReplyDelete
  57. Thanks Thanks Thanks Thanks Thanks Thanks Thanks Thanks!!!!!!!!

    Thanks a Ton!!!!!!!!!!!!!!!!!!

    ReplyDelete
  58. nice article. I would love to follow you on twitter. By the way, did anyone hear that some chinese hacker had hacked twitter yesterday again.

    ReplyDelete
  59. thanks a lot for the select_inner function :)

    ReplyDelete
  60. Hi. Thanks a lot. Your select_innerHTML save my brain and my win-PC)

    ReplyDelete
  61. muchas gracias!!!! me salvo la mañana

    ReplyDelete
  62. try this, it looks like a joke but it works

    xmldata = "x"; //Very very important
    xmldata += "(option value='xxx')aaa(/option)";
    xmldata += "(option value='yyy')yyy(/option)";
    xmldata += "(option value='zzz')zzz(/option)";
    xparent = form1.selectobject.parentElement
    xselect = form1.selectobject;
    xselect.innerHTML = "";
    xselect.innerHTML = xmldata;
    xparent.innerHTML = xselect.outerHTML;

    Bye

    ReplyDelete
  63. use jquery.
    http://jquery.com/

    it works!!

    good luck

    ReplyDelete
  64. Gr8!...select_innerHTML function worked for me...Thanks, Jenson (http://jenson.in/)

    ReplyDelete
  65. thank very much that's great for all browser

    ReplyDelete
  66. Hello Náiron,

    it's 2011 now and the bug is not fixed yet (I'm using IE 8 on XP pro.

    Thanks a lot for your function.

    Kind regards

    Mike (mike.holger@gmail.com)

    ReplyDelete
  67. Hi,
    Excellent post, it solved my issue.
    But it made the options also to lowercase.
    Did a small work around and the issue resolved.

    [code]
    //innerHTML = innerHTML.toLowerCase().replace(/<option/g,"<span").replace(/<\/option/g,"</span")


    innerHTML = innerHTML.replace(/<option/gi,"<span").replace(/<\/option/gi,"</span")

    [/code]

    Thanks,
    Thangaselvi

    ReplyDelete
  68. I must give you 1.000 beers for this. Thank you ! Thank you !Thank you ! You saved me and hours of work with this function. God bless you dude ! :)

    ReplyDelete
  69. Thanks man.. great post. saved the day...

    ReplyDelete
  70. Thanks a lot ! 5 years after your solution the bug is still not fix ...

    ReplyDelete
  71. No words to express my gratitude to you, with moist eyes and grateful heart a lots and lots of thank you - Arvind

    ReplyDelete
  72. Thanks a Ton!! Helped me a lot..!!! Thanks Again :-)

    ReplyDelete
  73. Thank you my friend for the nice post!

    ReplyDelete