jQuery autocomplete shows value instead of label
Asked Answered
S

2

11

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

Sue answered 24/4, 2016 at 22:32 Comment(0)
O
16

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.

Orobanchaceous answered 25/5, 2018 at 10:53 Comment(0)
M
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;
    }
});
Magnificent answered 24/4, 2016 at 23:4 Comment(2)
i dont want to kill focus completely. i just want #txt to show label instead of valueSue
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.Edgar

© 2022 - 2024 — McMap. All rights reserved.