Search code examples
jqueryinternet-explorer-9

Select option not dynamically set on IE9


I have looked at all the answers related to this, but still cannot figure out. Please help. I have a jquery code as below :

$('#DDPrimaryServiceLine').find('option:contains("' + rowData['Primary_Service_Line'] + '")').attr("selected", true);

rowData is generated from ajax through DB call. Also originally the select is empty ,it is getting dynamically populated at run time. By Default it has null as selected.

On running, the drop down displays default selected null in IE9, though it works perfectly well in Google Chrome.

Please suggest. (I tried writing

$("#DDPrimaryServiceLine option:selected").removeAttr('selected');

too in my code. But doesn't work )


Solution

  • Comment as answer:

    You should be setting the val() of the select and not selecting the option, however if you want to change the selected property of an option, use prop() and not attr(). This sets the correct internal values (and triggers selection changes) and does not just change the display attributes.

    e.g.

    $('#DDPrimaryServiceLine').find('option:contains("' + rowData['Primary_Service_Line'] + '")').prop("selected", true);
    

    prop has the added advantage that the values returned are not just strings and it will correctly return true and false boolean values if the attribute is "true" or "false".