codebrain codebrain - 3 months ago 14
HTML Question

How to set Default value in autocomplete implemented textbox?

I have a textbox implemented with autocomplete. Here is it.

<input id="txtcity" />
$("#txtcity").autocomplete({
source: function (request, response) {
$.ajax({
url: '@Url.Action("CityLookup", "PatientDemographic", "")', type: "POST", dataType: "json",
data: { searchText: request.term, maxResults: 10 },
success: function (data) {
response($.map(data, function (item) {
return { label: item.Text, value: item.Text, id: item.Value }
}))
}
})
},
select: function (event, ui) {
$("#CityCode").val(ui.item.id);
},
open: function () {
$(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function () {
$(this).removeClass("ui-corner-top").addClass("ui-corner-all");
}
});


This returns three results, let's say "Apple", "Banana", "Cabbage". How do I set a default value to "Banana" while rendering ? i.e, text="banana" value="2"?

Answer

you can set the value like this after initializing Autocomplete:

$( "#txtcity" ).autocomplete({
  // do whatever
}).val('Banana').data('autocomplete')._trigger('select');

Updated Example: http://jsfiddle.net/55jhx/1/

Comments