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"?
If you need to set the initial value for your Autocomplete component and then never programmatically update it again, the best option is the defaultValue prop. This prop accepts a value that only gets rendered until an option is selected from the Autocomplete's dropdown list.
By default its value is null. This option is used append an element to the menu. By default its value is null. When the value is null, the parents of the input field will be checked for a class of ui-front.
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/
Change your following line
$('#txtcity').val() = item.value;
to
$('#txtcity').val(item.text);
Trigger the click for the first element in the ul
to fire the select for autocomplete:
$("ul.ui-autocomplete li").first().trigger("click");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With