Reputation: 93
I am probably missing something obvious here. I am totally new to Chosen so plz bear my ignorance. I am using Chosen with Asp.NET MVC for a select multiple. It works fine when values are selected by user manually. However when I use an Ajax call to pre-select some values (that already exist in the option list that I use with Chosen) No selected values are posted.
Here what my code looks like
$.ajax({ type: "POST",
url: "/Project/GetProjectCrewMemberIds",
traditional: true,
//dataType:'json',
data: { projectId: selectedProject },
success: function (data) {
$('ul.chosen-choices').empty();
$.each(data, function (index, item) {
$('ul.chosen-choices').append('<li class="search-choice"><span>' + item.text + '</span><a class="search-choice-close" data-option-array-index="' + item.value + '"></a></li>');
});
// $("#SelectedCrewMembersId").trigger("chosen:updated");
},
error: function (xhr, status, exp) {
alert(exp);
}
});
the Ajax call works and I get the desired values.
When I use trigger("chosen:updated"); the select list gets empty. When commented I get the values added to the list but not posted.
Can anybody tell me what I missing here.
Thanks
Upvotes: 1
Views: 619
Reputation: 93
Eventually I found the solution, so hopefully this helps someone else :
$.ajax({
type: "POST",
url: "/Project/GetProjectCrewMemberIds",
traditional: true,
//dataType:'json',
data: { projectId: selectedProject },
success: function (data) {
// $('ul.chosen-choices').empty();
$.each(data, function (index, item) {
$("#SelectedCrewMembersId option[value='" + item.value + "']").prop("selected", true);
});
$("#SelectedCrewMembersId").trigger("chosen:updated");
},
error: function (xhr, status, exp) {
alert(exp);
}
});
It is just about updating the selected values in your '' and call .trigger("chosen:updated")
So instead of updating the "ul.chosen-choices" element of the chosen , just select the elements needed of the and call .trigger("chosen:updated"); will take care of the rest.
Upvotes: 2