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
I found your site via Google trying to fix the IE select bug. Thanks for posting that function, works a treat.
ReplyDeleteInteresting 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.
Another bad way of adding is
ReplyDeletevar selText = "(OPTION)(/OPTION)..... //Options as HTML
First
MySelects.innerHTML="";
MySelects.outerHTML= MySelects.outerHTML.replace("(/SELECT)",selText + "(/SELECT)");
Thanks anonymous.
ReplyDeleteit's 3:15 AM - you rock. I've been bashing my head against the keyboard for hours. Thanks!
ReplyDeleteFine and usefull solution, many thanks to you. Maybe you also had an idea about selecting an value at the option-list?
ReplyDeleteTried 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 :(
Hey last anonymous,
ReplyDeleteYou 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.
Thanks very much. Worked on this all day today at work. MSDN solutions didn't work for me. This did.
ReplyDeleteThank you!!
ReplyDeleteThanks for the nice post!
ReplyDeleteThanks!!! The function works great in IE
ReplyDeleteYou'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!
ReplyDeletePjotr from The Netherlands...
Thanks people. :)
ReplyDeleteYour script seem to solve a problem I have been battling with for quite some time now.
ReplyDeleteThanks.
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.
Sorry anonymous. I forget to explain how to use my script.
ReplyDeleteNow i'll update this post and show to use.
Thanks!
I now get it.
ReplyDeleteThanks for the timely update.
I've got large box loading from AJAX about 1000 items. On IE6 this code is then very slowly.
ReplyDeleteDo you see some way to expand speed?
Hi Aleksander.
ReplyDeleteTry to use the 'outerHTML' for IE.
A anonymous write about this in my second comment.
Thanks for that,
ReplyDeleteBut I still have a problem with:
field.childNodes.length
it is 0?!
Hi Aleksander.
ReplyDeleteNO, 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?
Yes, I found your function is useful but problem exists in IE with lot of items.
ReplyDeleteThen I try with outerHTML way and I can't set selected item.
Can we speed up your function?
Hi Aleksander
ReplyDeleteSend 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.
Hello,
ReplyDeletethx for this great function, its work very nice!
Thanks Micox-Náiron J. C. G.
ReplyDeleteYour script is good I've apply it successful
You can use outerHTML to fill the select then use script to select the correct option. It's still faster than using innerHTML.
ReplyDeletefor(var i=0; i<my_select.options.length; i++)
{
if (my_select.options[i].value == "select_me")
my_select.options[i].selected = true;
}
is this work for IE7?
ReplyDeleteyes
ReplyDelete(Volo Mike says...)
ReplyDeleteThis 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".
this is grt...did the job for me...Grt work!!
ReplyDeleteIf you have a lot of information to display in the select... it's faster to do it like that...
ReplyDeleteobject=document.getElementById('ElementId');
if(object!=null){
var inner = "(option value='test1')display1(/option)";
object.innerHTML=inner;
object.outerHTML=object.outerHTML;
}
Hi anonymous.
ReplyDeleteI tried with outerHTML but it have problems when i see the result innerHTML in future.
outerHTML just currectly work visually.
Thanks for suggest.
Hi Micox - Náiron J. C. G.!
ReplyDeleteThanks 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
Yeah Solen, post your link of the problem.
ReplyDeleteThanks.
Great,
ReplyDeleteThis was a lifesaver to me !
Hey Micox,
ReplyDeleteI'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>
a-HA!
ReplyDeleteFigured it out, thanks again Micox. Three days of wanting to break my monitor over the shortcomings of MSIE have been brought to an end.
This isn't the first time your code has saved me.
ReplyDeleteThanks!
Thanks people.
ReplyDeletefunction select_innerHTML(select, inner) {
ReplyDeleteselect.outerHTML = select.outerHTML.substring(0, select.outerHTML.indexOf(')', 0) + 1) + inner + '(/select)';
}
The same. Shorter.
Change '(' and ')' with properly rotated '^' ;)
I never write comments to stuff i find, but you just made my day. Many thanks and a beer for you mate!
ReplyDeletegreat fix!
ReplyDeletefinally a solution for that crappy IE bug
PS. Use open standards, use Firefox
obrigado !!!
ReplyDeleteyou were very helpful !!!!
Thanks, this topic solved my problem.
ReplyDeletevejam: http://support.microsoft.com/kb/276228
ReplyDeleteEsse 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
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.
ReplyDeletehey bro... the srcipt do its work very well, thnx
ReplyDeletebut... my options are ordered by an optgroup tag...
how can i fix the problem????
You can also do it like this - rewrite the whole select: let's say that you have
ReplyDelete<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>"
I meant document.getElementById('span1').innerHTML
ReplyDeleteabove, in my previous comment
This comment has been removed by the author.
ReplyDeleteThanks so much!
ReplyDeleteThanks buddy this is better solution than solution provided by Microsoft website
ReplyDeleteI 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.
ReplyDeleteThis 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?
ReplyDeletedidn't work for me,here is my scenario:
ReplyDeletei 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
Se podria usar esta función para cambiar dinamicamente el select con AJAX?
ReplyDeleteAlguna ayuda?
Si Raul, vea esto: http://www.webly.com.br/Micox/ajaxGo.htm
ReplyDeleteBravo, super script! ;)
ReplyDeleteawesome great one
ReplyDeletegood job ya man
it's working :-)
Hi,
ReplyDeletereally great stuff yar.......
nice one! thanks
ReplyDeleteThank you!!! This problem was driving me insane!!! f***** IE!!
ReplyDeleteI love you!!!!!!! This solution rocks!!
ReplyDeleteRan into the same problem using Ajax to filter dropdown based on first dropdown choice in IE.
ReplyDeleteEasy fix:
http://support.microsoft.com/kb/276228
Thank you for your usefull function, it saved me a lot of time.
ReplyDeleteI 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
Thanks Thanks Thanks Thanks Thanks Thanks Thanks Thanks!!!!!!!!
ReplyDeleteThanks a Ton!!!!!!!!!!!!!!!!!!
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.
ReplyDeletethanks a lot for the select_inner function :)
ReplyDeleteHi. Thanks a lot. Your select_innerHTML save my brain and my win-PC)
ReplyDeletemuchas gracias!!!! me salvo la mañana
ReplyDeletetry this, it looks like a joke but it works
ReplyDeletexmldata = "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
use jquery.
ReplyDeletehttp://jquery.com/
it works!!
good luck
Gr8!...select_innerHTML function worked for me...Thanks, Jenson (http://jenson.in/)
ReplyDeletethank very much that's great for all browser
ReplyDeleteHello Náiron,
ReplyDeleteit'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)
Hi,
ReplyDeleteExcellent 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
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 ! :)
ReplyDeleteThanks man.. great post. saved the day...
ReplyDeleteThanks a lot ! 5 years after your solution the bug is still not fix ...
ReplyDeleteNo words to express my gratitude to you, with moist eyes and grateful heart a lots and lots of thank you - Arvind
ReplyDeleteThanks a Ton!! Helped me a lot..!!! Thanks Again :-)
ReplyDeleteThank you my friend for the nice post!
ReplyDelete