I have a problem with jQuery UI. I need to autocomplete()
a form with data from database. I need name
, for display, and ID
, for submit.
So, i can't simply use an array of string with name, i need to use array of object. My problem is this : jQuery UI autocomplete ONLY accept label
or value
properties to perform auto-completion. So, i have to do that :
PHP
:
public function autocomp(Connection $db)
{
$term = $_GET['term'];
$req = $db->prepare("SELECT name, id FROM product LIKE '%".$term."%'");
$req->execute();
// Because jQuery-UI's autocomplete() accept only array with 'label' for index of value,
// We are forced to parse the data before send it to JSON...
$array = [];
$i = 0;
while($data = $req->fetch())
{
$i++;
$array[$i]['id'] = $data['id'];
$array[$i]['label'] = $data['name'];
}
$response = new Response(json_encode($array));
return $response;
}
jQuery autocomplete()
:
$(function () {
$('#autotry').autocomplete({
source: '/autocomp',
select: function (event, ui) {
$('#hidden').val( ui.item.id)
}
});
});
Do you know what i mean ? Yeah, if 'label' or 'value' is defined, i can use other properties (like 'id') for do what i want.
I just want to use custom properties, for avoid that loop... For each input. Thank you, and please excuse my english (and my JS skill.)