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

前端 未结 3 2058
走了就别回头了
走了就别回头了 2021-02-20 05:30

I´m trying to use the JQuery UI Autocomplete plugin (click to see the demo page of JQuery UI Autocomplete plugin)

I´m using as datasource a list of objects as bellow:

相关标签:
3条回答
  • 2021-02-20 05:34

    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.

    0 讨论(0)
  • 2021-02-20 05:42

    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;
            }
    
    0 讨论(0)
  • 2021-02-20 05:48

    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;
      }
    });​
    
    0 讨论(0)
提交回复
热议问题