I have a dynamic select that needs to be driven off another select, but I cannot seem to get it working in IE (using IE9). I’ve seen this post here but (unless I’m not understanding it) this didn’t seem to help: Dynamic Related Selects with jQuery, not work in IE.
I’ve really simplified it so that it’s easy to understand the problem. I have 2 selects, and 1 drives the other. So, when you select something in the first one, the second one changes. For this example I’m just adding a new item to the select and even this doesn’t work in IE:
var mydiv = $("#testdiv");
$("<select id='f1'>").appendTo(mydiv);
$("<select id='f2'>").appendTo(mydiv);
$("#f1").append("<option value='1'>1</option>");
$("#f1").append("<option value='2'>2</option>");
$("#f2").append($("<option>").attr("value", "n"));
$("#f1").change(function () {
$("#f2").append("<option value='t1'>t1</option>");
});
<div id="testdiv"></div>
So, in theory we should start with 2 select lists and “f2” will 1 blank option in it.
Next, select an item from “f1” and it will add a new option to “f2”.
This works exactly as I want in firefox and chrome. In IE it just behaves oddly. Take this example in IE:
Scenario 1
- I open the page and check the “f2” select. It has 1 blank value
- I select an item in “f1”
- I check “f2” and it still has 1 blank value
Scenario 2
- I open the page and don’t touch the “f2” select.
- I select an item in “f1”
- I check “f2” and it has 2 items!
- I select another item in “f1”
- I check “f2” and it still has 2 items?!?
So it looks like the first time I activate the select control it must do something with the existing HTML… and now that’s all it’s going to render from here on…
This is driving me nuts, what am I doing wrong?!?
Note: Not sure if it matters, but both of the selects are dynamically generated using javascript/jquery because I don’t know their values until an async call completes.
Updated question due to investigation through comments… Seems my last note on the dynamic creation of the objects was crucial to recreating the problem
Figured it out. Read on a few websites about some bugs with selects in IE and having to use divs as a workaround. So the solution is to repost the html in the div each time you want to refresh the list. Something like this:
The important part being “testdiv2” and populating it with the html from “tempdiv”. Might be a neater way to do this but in the mean time the above works for me. Here’s a working solution in jsfiddler: http://jsfiddle.net/VHPt5/4/
Update
Also, a slightly different way to achieve the same thing as posted in a comment by @Ingenator in a different answer below. Rather than replacing the HTML like this:
You can clear the original div and re-append it:
Ultimately, the same solution, but removing the need to generate a tempdiv in order to replace the html of the first div.
Solution here: http://jsfiddle.net/cAr57/3/