Using jQuery's autotomplete widget, I would like to add one item if no criteria is matched. That item is added just fine but the problem I'm facing is that I can't set that item's value to null
. what I'm getting is the item's value
with the same text as the label
Sample code:
source: function(request, response)
{
//suggestions prefilled via AJAX...
var items = [];
if(suggestions.length)
{
for(var i in suggestions)
{
var item = suggestions[i];
item.value = suggestions[i].id;
item.label = suggestions[i].text;
items.push(item);
}
}
else
{
var item = {
value : null,
label : "some text..."
};
items.push(item);
}
response(items);
}
When I console the selected item, this is what I get:
select: function(event, ui)
{
console.log(ui.item.value);
//if item's value was set to null, then label
//if item's value was set to 0, then label
//if item's value was set to "", then label
//if item's value was set to 123, then 123
}
EDIT: apparently this worked at some point in history...
In this fiddle with latest jquery and jquery ui the problem is present, but in this one with jquery 1.10.4 was the last jquery ui that worked the way I want.
The short answer, it seems to ignore it when you have 1 item in the list to select from.
Example:
https://jsfiddle.net/Twisty/6oa0yg24/2/
$(function() {
var items = [{
value: 1,
label: 'neo'
},
{
value: 2,
label: 'trinity'
},
{
value: 3,
label: 'morpheus'
},
{
value: null,
label: 'smith'
},
{
value: undefined,
label: 'switch'
},
{
value: "",
label: 'tank'
}
];
$("#autocomplete").autocomplete({
source: items,
select: function(e, ui) {
console.log(ui.item.value);
}
});
});
If we type t
, we get a few hits, and select smith
, the value is left empty. If we type sm
, and now the only option is smith
, "smith" is then added as the value. Why? I don't know, but I tested all three scenarios, and each does it. Pretty sure it comes down to these lines (5864 - 5869 in https://code.jquery.com/ui/1.12.1/jquery-ui.js):
// reset the term after the select event
// this allows custom select handling to work properly
this.term = this._value();
this.close( event );
this.selectedItem = item;
I suspect you can overwrite it with Widget Factory if you are so inclined.