10

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

Govind Samrow
  • 9,981
  • 13
  • 53
  • 90

2 Answers2

12

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.

Code Reaper
  • 143
  • 1
  • 9
8

you have 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;
    }
});
Hakkı
  • 811
  • 2
  • 13
  • 23
  • i dont want to kill focus completely. i just want #txt to show label instead of value –  Apr 24 '16 at 23:17
  • This solution (specifically, returning false for the focus event) is useful if you don't want to show the label or the value and would rather just prefer to leave the textbox contents as-is until an item is selected. – Taraz Dec 22 '21 at 01:02