cubanGuy
cubanGuy

Reputation: 1296

Set selected option in dropdown using jQuery not working on IE

I have two dropdown lists created dynamically and I'm trying to set the default "selected" option using jQuery. It works perfectly in Chrome, but I can't get it to work in IE9.

This what I've tried so far: JS

 $("#dropdown").append($('<option>', {
                value: 'All',
                text: 'All'
            })).prepend($('<option>', {
                value: 'Select Fiscal Year',
                text: 'Select Fiscal Year',
                select: 'selected'
            }));
  $("#dropdownRO").prepend($('<option>', {
                value: 'Select RO',
                text: 'Select RO'
            })).attr("selected", true).append($('<option>', {
                value: 'All',
                text: 'All'
            }));

As you can see I tried different ways for each dropdown to see which one worked. I also tried to use .attr("selected", "selected"), but the same. Is there anything I'm missing that would make this simple thing work in IE? Thanks!

Upvotes: 0

Views: 1310

Answers (2)

cubanGuy
cubanGuy

Reputation: 1296

The only way I could find to make this work was by adding .val('Selected RO'); at the end of the chain:

 $("#dropdown").append($('<option>', {
 value: 'All',
 text: 'All'}))
 .prepend($('<option>', {
 value: 'Select Fiscal Year',
 text: 'Select Fiscal Year',
 selected: 'selected'}))
 .val('Select Fiscal Year');

 $("#dropdownRO").prepend($('<option>', {
 value: 'Select RO',
 text: 'Select RO'}))
 .prop("selected", true).append($('<option>', {
 value: 'All',
 text: 'All'}))
 .val('Select RO');

Now it works, both in Chrome and IE. If anyone has a better solution, please share. Thanks!

Upvotes: 0

Barmar
Barmar

Reputation: 780871

In the first block, you're setting the select attribute, when it should be selected.

$("#dropdown").append($('<option>', {
    value: 'All',
    text: 'All'
})).prepend($('<option>', {
    value: 'Select Fiscal Year',
    text: 'Select Fiscal Year',
    selected: 'selected'
}));

In the second block, you're applying .attr() to $("#dropdownRO"), not the <option> that you're adding (check the parentheses). It should be:

$("#dropdownRO").prepend($('<option>', {
    value: 'Select RO',
    text: 'Select RO'
    }).attr("selected", true)).append($('<option>', {
    value: 'All',
    text: 'All'
}));

I suggest you do both of them consistently. I'm just showing the two different ways to write this.

Upvotes: 3

Related Questions