Reputation: 4701
I think IE hates me. Everything I do in other browsers works, but IE 11, no! It is failing. I'm guessing it's me and not the browser.
I have a <select>
list on my web page, and I'm trying to bind the <option>
dynamically.
So far, it works great in Firefox and Chrome, but not in IE. There is no error in the IE Development tools (F12) so I'm lost as to why it refuses to work.
HTML
<select id="MyList">
</select>
Javascript
$(function() {
var myItems=[];
myItems.push({"All":"Hello"});
myItems.push({"One":"And More"});
myItems.push({"Two":"Lots More"});
for (i = 0; i< myItems.length;i++) {
for (item in myItems[i]) {
var x = myItems[i][item]; //for my testing
var y = myItems[item]; //for my testing
$("#MyList").append("<option>" + item + "</option>");
}
}
});
If you try the fiddle in FF or Chrome, all good. The select
list populates with All, One and Two.
Short of a gift or even some form of sacrifice to the IE elves, what do I need to do to make IE happy with me?
Upvotes: 0
Views: 84
Reputation: 885
var sel = $("#MyList");
sel.empty();
for (var i = 0; i< myItems.length;i++) {
for (var item in myItems[i]) {
var x = myItems[i][item];
var y = item;
console.log(x);
console.log(y);
sel.append('<option value="' + x + '">' + y + '</option>');
}
}
As already mentioned by @ T.J.Crowder in IE 10 jquery1.10.1 is not working and updating the jquery version to later it started to work;
Upvotes: 0
Reputation: 1075755
This is bizarre. When I run that fiddle in the IE I have handy (IE9), I get an "access denied" error and jQuery isn't loaded. If I change the fiddle to use 1.11.0 rather than 1.10.1, I don't get that error and the script runs.
There are a couple of issues with the code, primarily undeclared variables (your code was falling prey to The Horror of Implicit Globals); here's an updated fiddle with:
Here's the code:
$(function() {
var myItems=[];
myItems.push({"All":"Hello"});
myItems.push({"One":"And More"});
myItems.push({"Two":"Lots More"});
var i, item;
for (i = 0; i< myItems.length;i++) {
for (item in myItems[i]) {
var x = myItems[i][item];
var y = myItems[item];
$("#MyList").append("<option>" + item + "</option>");
}
}
});
Separately, though, to be compatible with a wider range of browsers, you might want to use the Option
constructor and the add
method of the options
list rather than appending a DOM element; some older browsers prefer it. That looks like this: Fiddle
// Before the loop...
var options = $("#MyList")[0].options;
// ...in the loop
options.add(new Option(item));
Upvotes: 4
Reputation: 100
Try this
$(function() {
var myItems=[];
myItems.push({"All":"Hello"});
myItems.push({"One":"And More"});
myItems.push({"Two":"Lots More"});
for (i = 0; i< myItems.length;i++) {
for (item in myItems[i]) {
var x = myItems[i][item];
$('#MyList')
.append($("<option></option>")
.attr("value",x)
.text(item));
}
}
});
Upvotes: -2