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

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

  •  01-06-2022
  •  | 
  •  

문제

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?

도움이 되었습니까?

해결책 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);

다른 팁

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

$("#LicenseId").append(data).attr("selected", "selected");
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top