Cześć,
Tworzę obiekt option i dodaję go do selecta:
$(new Option(this[$(that).attr('data-display-value')], this[$(that).attr('data-value')], true)).appendTo('#'+$(that).attr('data-id'));
W trzecim parametrze dodaję true, i przy odpowiedniej opcji pojawia się selected, jednakże w select'cie nie jest on domyślnie wybrany.
Cały proces tworzenia tego pola wyboru jest następujący:
-odczytanie wartości z elementu p.
-ajaxowe pobranie danych do opcji
-stworzenie elementu select
-stworzenie nowych opcji
Poniżej zamieszczam jeszcze kod, jednak z nim chyba nie ma problemu (jak już to z kolejnością) ponieważ wszystko wykonuje się poprawnie.
$('#start-edit-task').click(function(){
editingTask = true;
$('.editable').each(function(){
switch($(this).attr('data-type')){
case "textarea":
string = '<textarea id="'+$(this).attr('data-id')+'" style="resize:vertical;" class="form-control removable">'+$(this).text()+'</textarea>';
$(this).after(string);
$(this).hide();
break;
case "select":
that = this;
$.ajax({
url: 'tasks/'+$(this).attr('data-ajax')
})
.done(function(e){
string = '<select id="'+$(that).attr('data-id')+'" class="form-control m-b removable">';
$(that).after(string);
$(that).hide();
data = $.parseJSON(e);
$(data).each(function(){
if($(that).attr('data-selected') == this[$(that).attr('data-value')]){
$(new Option(this[$(that).attr('data-display-value')], this[$(that).attr('data-value')], true)).appendTo('#'+$(that).attr('data-id'));
} else {
$(new Option(this[$(that).attr('data-display-value')], this[$(that).attr('data-value')])).appendTo('#'+$(that).attr('data-id'));
}
});
});
break;
}
});
$('#cancel-edit-task').show();
$('#save-edit-task').show();
$('#start-edit-task').hide();
});
PS wiem że długi i brzydki :(