Reputation: 2784
I'm using jQuery 3.3.1 and jQuery-ui 1.12.1. I have an input field where an user should choose among objects of an array, previously retrieved with an ajax call and stored in a variable.
The documentation of the source option of autocomplete says that if a function is provided to filter the terms, it should return an array of strings to make the user choose from.
I'd like to separate the view (the string that I display to the user) from the data, the object beneath it. I've seen that I can return an array of objects {label: 'string to display', value: the_object}
from the source option, and the label is correctly displayed, but when the user selects it, it turns into an anonymous string [object Object]
.
Having the label string in the input field after the selection would be great, but it could be ok just showing the terms as they are, without any replacement; otherwise I'd like to have the field cleared, and I thought to clear it with:
select: function(event, ui) {
var _content = ui.item; // Store the content of the field somewhere.
$(event.target).val('');
}
but .val('')
doesn't work, nor does .val(null)
.
Here's a test fiddle: https://jsfiddle.net/xpvt214o/16284/
Upvotes: 1
Views: 817
Reputation: 2784
The solution I found, inspired by @CertainPerformance answer, is to store the original dictionary object with a different key, such as orig_obj
, so that I can then work directly on it in the select
method.
In this way, the label
string is displayed when the user selects the label, but we can manipulate the object in its original form.
Fiddle: https://jsfiddle.net/xpvt214o/16356/
Upvotes: 0
Reputation: 370689
Have the elements_that_match
object's value be the string you want, not an object.
elements_that_match.push({"label" : _label, "value" : element_obj});
to
elements_that_match.push({"label" : _label, "value" : element_obj.name + ', ' + element_obj.country });
https://jsfiddle.net/xpvt214o/16303/
Upvotes: 1