JQuery UI Autocomplete - How to select an item and mantain the label (not the value) in the input text

眉间皱痕 提交于 2019-12-04 02:52:50

Since I just had to solve this too. I thought I would show my solution. IMHO it is cleaner since you don't need the separate OnSelect and OnFocus functions. (though it really does the same thing as what rperson ended up doing)

$('#txtCidade').autocomplete({
  source: availableTags,
  focus: function(event, ui) {
    $(this).val(ui.item.label);
    return false;
  },
  select: function(event, ui) {
    $('#hidCidade').val(ui.item.value);
    $(this).val(ui.item.label);
    return false;
  }
});​

Change your autocomplete call to the following:

$("#txtCidade").autocomplete({
    source: availableTags,
    select: function(event, ui) {
         $("#hidCidade").val(ui.item.label);
    }
});​

#txtCidade should automatically pckup the selected label when an autocomplete item is clicked on.

See a jsFiddle example here.

I´ve solved the issue creating the handlers for OnFocus and OnSelect and returning false in each one.

        function OnFocus(event, ui)
        {
            $( "#txtCidade" ).val( ui.item.label );
            return false;
        }

        function OnSelect(event, ui)
        {
            var item = ui.item;
            var itemLabel = item.label;
            var itemValue = item.value;
            var campo = $("#txtCidade");

            $("#hidCidade").val(itemValue);
            $("#txtCidade").val(itemLabel);

            var campoValue = campo.val();
            var hidCampoValue = $("hidCidade").val();
            return false;
        }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!