Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"?

like image 662
Sakthivel Avatar asked Jun 12 '13 07:06

Sakthivel


People also ask

How do I set default value in Mui autocomplete?

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.

What is the default value of Append to option of autocomplete () method?

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.


3 Answers

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/

like image 103
Edward Avatar answered Oct 27 '22 03:10

Edward


Change your following line

 $('#txtcity').val() = item.value;

to

 $('#txtcity').val(item.text);
like image 45
Vishwanath Avatar answered Oct 27 '22 01:10

Vishwanath


Trigger the click for the first element in the ul to fire the select for autocomplete:

$("ul.ui-autocomplete li").first().trigger("click");
like image 21
user3711504 Avatar answered Oct 27 '22 01:10

user3711504