Coding Problem :
I have two inputs
, I’m using automplete
in only one. The autocomplete code:
$(document).ready(function() {
$.getJSON('include/funcoes/carrega_cidades.php', function(data){
var dados = [];
$(data).each(function(key, value) {
dados.push(value.name);
});
$('#cidade').autocomplete({ source: dados, minLength: 3});
});
});
cidade
is the input
that has autocomplete
and is returning normally.
I need to bring in another input
id_cidade
, the city ID returned in autocomplete.
SQL:
$pdo = new PDO("mysql:host=localhost; dbname=iboard; charset=utf8;", "root", "");
$dados = $pdo->prepare("
SELECT
id,name
FROM
cidade
");
$dados->execute();
echo json_encode($dados->fetchAll(PDO::FETCH_ASSOC));
How can I do this?
Answer :
Answer 1 :
Simple, in jQuery UI, for you to have the value searched in the database being displayed in the list generated by autocomplete, you do not always have to use an array of string, but you can use an array of objects, since it has the attribute label
as the desired value for display in the list generated by autocomplete.
For example:
['wallace', 'rray', 'bigown']
Can be used as:
[{label: 'wallace', id: 1}, {label: 'rray', id: 2}]
So you can access other attributes through ui.item
.
Example:
$.getJSON('include/funcoes/carrega_cidades.php', function(data){
var dados = [];
$(data).each(function(key, value) {
dados.push({label: value.name, id: value.id});
});
$('#cidade').autocomplete({
source: dados,
minLength: 3,
select: function (event, ui) {
if (ui.item && ui.item.id) {
$("#cidadeID").val(ui.item.id);
return false;
}
},
});
});
});
Answer 2 :
source
of data It will look like this:
$.getJSON('include/funcoes/carrega_cidades.php', function(data){
var dados = data;
$('#cidade').autocomplete({ source: dados, minLength: 3,
select: function (event, ui) {
if (ui.item && ui.item.id){
$("#cidadeID").val(ui.item.id);
return false;
}
}
}).autocomplete( "instance" )._renderItem = function( ul, item ) {
return $("<li>").append(item.name).appendTo(ul);
};
});
Reference:
JQUERY UI Doc’s
Answer 3 :
Answer 4 :
Answer 5 :
Answer 6 :
Answer 7 :
Answer 8 :
Answer 9 :