Jquery dynamically append option to a selectlist and then make the new option selected

StackOverflow https://stackoverflow.com/questions/17263721

  •  01-06-2022
  •  | 
  •  

Question

I am dynamically adding an option to a selectList and trying to make it the selected item but the following code does not seem to make the option selected. It does ad the option, however.

$("#LicenseId").append(data).prop("selected", true);

What am I doing wrong, please?

Was it helpful?

Solution 2

You need to unselect the currently selected option first:

var d = $('<div />').append(data).find('option').prop('selected', true);

$("#LicenseId").find('option').removeProp('selected').end().append(d);

OTHER TIPS

Aside from using prop, you could also try the attr method.

$("#LicenseId").append(data).attr("selected", "selected");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top