I am using the code for autocomplete below. I type the initials of a fruit and my select returns with the names of the fruits that match those initials. Selecting one of them, I get the id and play in another field. So far the problem is that I wanted it if nothing was found, clear the field with id.
Example:
I open the form and fill in "ma" will appear papaya and if I select papaya the cod 1 goes to the field idFruta
off and type "li" appears lemon and idFruta
is filled with 2 that everything is working .
Now if you type "zz" nothing appears, just the message "fruit not found" but my idFruta
field remains with id
of the fruit selected previously. I then wanted to select "No Fruit" to clear my field idFruta
.
Can you do that?
jQuery.fn.autoCompleteEditora = function (idCod, idFocus, formAddFruta) {
$(this).autocomplete({
appendTo: formAddFruta,
source: function (request, response) {
$("#loadingFruta").show();
$.ajax({
url: '../fruta/frutas.json',
type: "GET",
dataType: "json",
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
data: {
q: request.term
},
success: function (data) {
if (!data.length) {
var result = [
{
label: 'Fruta inexistente' ,
value: response.term
}
];
response(result);
} else {
response($.map(data, function (item) {
return {
label: item.nome,
id: item.cod,
abbrev: item
};
}));
$("#loadingFruta").hide();
}
}
});
},
minLength: 2,
focus: function (event, ui) {
$(this).val(ui.item.label);
return false;
},
select: function (event, ui) {
cod = ui.item.abbrev.cod;
idCod.val(cod);
(idFocus !== null) ? idFocus.focus() : idCod.focus();
}
});
$["ui"]["autocomplete"].prototype["_renderItem"] = function (ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append($("<a></a>").html(item.label))
.appendTo(ul);
};
};