jqueryinternet-explorer-8html-select

jQuery .val() on option in ie8?


I am dynamically adding a new option to a select list, and all I want to do is select it, as it comes from user input. Odds are, they want the new option they just added.

var msg = "an ajax return from a modal input that works";
$("#myselect").append( $('<option></option>').val(msg).html(msg) );

The item does get added to the select, but it is not selected.

I only have ie8 to test with, and comply with, on internet networks...

is this a browser bug, or is my code wrong?

my understanding was that .val() should select it.


Solution

  • changing the options value doesn't set the select to that value, you have to set the selects value to do that

    var msg = "an ajax return from a modal input that works";
    
    $("#myselect").append( $('<option>' + msg + '</option>') ).val(msg);
    

    Or you can set the selected property, but you would have to make sure no other options are selected :

    var option = $('<option />', {text:msg, selected:'selected'});
    $("#myselect").find('option').prop('selected', false).end().append( option );