jQuery autocomplete shows value instead of label

为君一笑 提交于 2019-12-12 08:59:04

问题


I am using jQuery-ui autocomplete. Here is how i use it

<form action="go.php" method="post">
    <input id="txt" type="text" />
</form>

<script>
    $('#txt').autocomplete({
         source: [{'label': 'milan', 'value': '1'}, {'label': 'minos', 'value': '2'}]
    })
</script>

When i type 'mi', milan and minos shows up.No problem with that. However when i focus on them with down key value of #txt changes to 1(value for milan) instead of milan. How can i show milan when i focus on it. Thanks


回答1:


Because the default behavior of the select event is to show the value not the label, so you need to simply:
- return false as "İsmail Hakkı Şen" mentioned earlier.
- or you can use event.preventDefault() to prevent the default action of the event from executing and then write down what you need to do as follows:

$('#txt').autocomplete({
     source: [{'label': 'milan', 'value': '1'}, {'label': 'minos', 'value': '2'}],
    focus: function( event, ui ) {
      event.preventDefault();
      $('#txt').val(ui.item.label);
    },
    select: function( event, ui ) {
     event.preventDefault();
     $('#txt').val(ui.item.label);
    }
});

Please refer to "Andrew Whitaker" answer in this post > Autocomplete applying value not label to textbox - as it is really helpful in understanding.




回答2:


you has to tell your code on focus to do something.

$('#txt').autocomplete({
     source: [{'label': 'milan', 'value': '1'}, {'label': 'minos', 'value': '2'}],
    focus: function( event, ui ) {
      $(this).val(ui.item.label);
      return false;
    },
    select: function( event, ui ) {
     $(this).val(ui.item.label);
      return false;
    }
});


来源:https://stackoverflow.com/questions/36829657/jquery-autocomplete-shows-value-instead-of-label

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!