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

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

  •  01-06-2022
  •  | 
  •  

Domanda

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?

È stato utile?

Soluzione 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);

Altri suggerimenti

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

$("#LicenseId").append(data).attr("selected", "selected");
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top