2
I am using the code for autocomplete below. I type the initials of a fruit and my select returns the names of the fruits that match those initials. Selecting one of them, I take the id and play in another field. So far the problem works is that I wanted that 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 Cod 1 goes to the field idFruta
delete and type "li" appears lemon and the idFruta
is filled with 2 this is all working.
Now if you type "zz" nothing appears, only the message "fruit not found" but my field idFruta
remains with the id
from the previously selected fruit. I wanted then that by selecting "Nonexistent Fruit" clear my field idFruta
.
You can do it?
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);
};
};
When you say "fruit not found" what appears is "Fruit not found"? That’s where you see if there is or is not certain?
– Miguel
That’s right. I’ll correct the text.
– Marcia Pereira Reis
It would also help if you put html here to see the elements you refer to etc... You can put it here if you like: https://jsfiddle.net/ with the functionality it has so far
– Miguel
Adds the function
response
here too.– relaxeaza
Are you sure it was you who wrote this code, because for me the solution is so obvious that I can’t believe that someone who developed all this logic, does not know where the value of the field remains.... But here’s a clue. In the code block where you add "Nonexistent Fruit"... add something like "idCod.val(');" Since I don’t know if idCod is global, nor the input id, I can’t post a code as a response.
– mau humor
@mauhumor I didn’t do it. That’s why I’m asking for help.
– Marcia Pereira Reis