Reputation: 3888
I'm trying to implement Autocomplete. So far I've overcome an obstacle: displaying custom information along the selectable items. For that matter, I'm passing the data with a JSON object. It's like this:
[{"codigo":"XL","descripcion":"Extra Large"},{"codigo":"M","descripcion":"Medium"},{"codigo":"S","descripcion":"Small"},{"codigo":"L","descripcion":"Large"}]
Now the initializing code is:
$this->template->add_js("$.getJSON(\"".base_url('talles/listar')."\",
function(data)
{
$('#txt_talle')
.autocomplete(
{
minLength: 0,
source: data,
focus: function(event, ui) {
$('#txt_talle').val(ui.item.codigo);
return false;
},
select: function(event, ui) {
$('#txt_talle').val(ui.item.codigo);
return false;
}
})
.focus(function(){ $('#txt_talle').autocomplete('search') })
.data('autocomplete')._renderItem = function(ul, item) {
return $('<li></li>')
.data('item.autocomplete', item)
.append('<a>' + item.codigo + '|' + item.descripcion + '</a>')
.appendTo(ul);
}
;
});", 'embed');
But now the problem is that the search is not working. I'm guessing that is does not work because it searches the objects, not inside the objects. I'd like to make it search among the item.codigo values. Is there a way to do this?
Upvotes: 2
Views: 125
Reputation: 1272
Maybe add it like this
$.getJSON("URL", function(data){
var autoc = [];
for (row in data) {
if (data.hasOwnProperty(row)) {
autoc[] = {
'label': row.codigo,
'value': row.descripcion
}
}
}
$('#txt_talle').autocomplete({
minLength: 0,
source: autoc,
focus: function(event, ui) {
$('#txt_talle').val(ui.item.codigo);
return false;
},
select: function(event, ui) {
$('#txt_talle').val(ui.item.codigo);
return false;
}
}).focus(function(){
$('#txt_talle').autocomplete('search')
}).data('autocomplete')._renderItem = function(ul, item) {
return $('<li></li>')
.data('item.autocomplete', item)
.append('<a>' + item.codigo + '|' + item.descripcion + '</a>')
.appendTo(ul);
};
});
I'm creating a new object based on your data object feeding the right label, value keys, as per @Nick Fishman's Answer
Upvotes: 0
Reputation: 654
Take a look at the "source" option in the jQuery Autocomplete widget: http://api.jqueryui.com/autocomplete/#option-source. It either expects an array of strings, or an array of objects with label
and value
properties.
Try adding label
and value
properties to each item of the JSON array returned in the talles/listar server call.
Upvotes: 4