jQuery UI autocomplete shows value instead of label in the input field

妖精的绣舞 提交于 2019-12-03 04:34:16

if you want the label to be your value, just have the source be

var ac = ["One Thing", "Two Thing"]      

alternatively, the select method of autocompletes default action is to put the value object (if specified) as the value of your input. you could also put event.preventDefault() in the select function and it will put the label as the value (as you have)

select: function( event, ui ) {
        event.preventDefault();
        $("#search").val(ui.item.label);
        PK.render(ui.item.value);
    }

If you want your label to be your value in the text box onFocus AND onSelect use this code:

select: function(event, ui) { 
        $('#hiddenid').val(ui.item.value); 
        event.preventDefault(); 
        $("#search").val(ui.item.label); },

focus: function(event, ui) { 
       event.preventDefault(); 
       $("#search").val(ui.item.label);}

I was missing the onFocus event (only setting the onSelect event). Thus, the value continued to show in the text input.

I was still haveing a problem with arrow keys showing the values. So I actually found it better to assign both the value and label to the label, and then put the value on a 3rd property of the data. For example let's put it on id.

var ac = [
    {
        label: "One Thing",
        value: "One Thing",
        id: "One-Thing",
    },
    {
        label: "Two Thing",
        value: "Two Thing",
        id: "Two-Thing"
    },      
]

Then when you use the select event, you can get id from ui:

select: function( event, ui ) {
    PK.render(ui.item.id);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!