Mike De Greef
Mike De Greef

Reputation: 21

How to change the value output of a autocomplete into the label output in jquery?

I'm starting to learn jQuery. But I can't find the solution to this "simple" problem? When I choose a "label" in my autocomplete inputbox, it eventually displays the "value". But I want the "label" to stay in that input box and the "value" I want to put in a hidden inputbox. This is my code for autocomplete for the moment:

$("#input_autocomplete").autocomplete({
minLength: 2,
source: availableTags,
change: function(e, ui) {
    if (!ui.item) {
        $(this).val("");
    }
},
response: function(e, ui) {
    if (ui.content.length == 0) {
        $(this).val("");
    }
}
}).on("keydown", function(e) {
if (e.keyCode == 27) {
    $(this).val("");
}
});

Upvotes: 2

Views: 627

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337656

To do what you require you can retain the array of label/value objects used to populate a jQueryUI Autocomplete, but map() it to a flat array of just the label contents. This avoids the value being set when an items is selected.

Then when an item is selected you can use filter() to lookup that value in the original array to find its value. Then you can manually update the form control with that.

Try this example:

let availableTags = [{ label: "Foo", value: 1 }, { label: "FooBar", value: 2 }, { label: "Bar", value: 3 }, { label: "BarFoo", value: 4 }]
let $hiddenValue = $('#hidden-value');

$("#input_autocomplete").autocomplete({
  minLength: 2,
  source: availableTags.map(t => t.label),
  select: function(e, ui) {
    let id = availableTags.filter(tag => tag.label === ui.item.label)[0].value;
    $hiddenValue.val(id);
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" />
<input type="text" id="input_autocomplete">
<input type="text" id="hidden-value" readonly />

Upvotes: 1

Related Questions