Reputation: 578
I would like to get the row id of selected item in my autocomplete
function, I get the values of my source from a php
variable.
<script>
$(function() {
var availableTags = [ <? php echo($toto); ?> ];
$("#foo").autocomplete({
source: availableTags
});
});
</script>
I already tried this function but it does not seem to work. In fact, when I add it to my script, my autocomplete
won't work anymore.
<script>
$(function () {
var availableTags = [ <? php echo($ListeNomsFormateeFinale); ?> ];
$("#nomClient").autocomplete({
source: availableTags
select: function (event, ui) {
$("#textfield1").val(ui.item.label); // display the selected text
$("#textfield2").val(ui.item.value); // display selected id
return false;
}
});
});
</script>
What am I doing wrong here? and is there a quick fix to this problem?
Edit:
I actualy needed to add a comma after source: availableTags
, I also deleted the return false
. but it dosen't return the id of the selected row, it actually writes the same value in the two textfields textfield1
and textfield2
Upvotes: 2
Views: 6472
Reputation: 137
From : Api Jquery UI - Autocomplete - option source
Array: An array can be used for local data. There are two supported formats:
An array of strings: [ "Choice1", "Choice2" ]
An array of objects with label and value properties: [ { label: "Choice1", value: "value1" }, ... ] The label property is displayed in the suggestion menu. The value will be inserted into the input element when a user selects an item. If just one property is specified, it will be used for both, e.g., if you provide only value properties, the value will also be used as the label.
The second point (2.) give a way to store the "id" (or something else) of the selected object. By example :
var yourSource = [ { label: "Choice1", id: "id1" } ];
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<link href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet" />
<form>
<input type="text" id="fooInput" />
</form>
<div id="result">
</div>
<script type="text/javascript">
var yourSource = [
{
label: "A",
id: "id1"
},
{
label: "B",
id: "id2"
}];
$("#fooInput").autocomplete({
source: yourSource,
select: function(event, ui) {
var e = ui.item;
var result = "<p>label : " + e.label + " - id : " + e.id + "</p>";
$("#result").append(result);
}
});
</script>
So try to format your data source like this :
var source = [ {label:"Foo", id:"1"}, ... ];
Upvotes: 3