Reputation: 624
[Sorry, for my Bad on English]
I would like to know, how can i get the id from array of object using JQuery UI Autocomplete.
It displays the name. But, i want to get the id when i click on submit button.
This is what i have been trying so far.
var cities = [
{
id: 1,
name: "New York"
},
{
id: 2,
name: "London"
},
{
id: 3,
name: "Jakarta"
},
{
id: 4,
name: "Sidney"
},
{
id: 5,
name: "New Delhi"
},
{
id: 6,
name: "Tokyo"
},
{
id: 7,
name: "Madrid"
}
];
var city_name = [];
for (var i = 0; i < cities.length; i++) {
city_name.push(cities[i].name);
}
$("#autocomplete").autocomplete({
source: city_name
});
var getResult = function() {
var x = document.getElementById("autocomplete").value;
document.getElementById("result").innerHTML = x;
}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>autocomplete demo</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.12.4.js"></script>
<script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
The result is
<div id="result"></div>
<hr>
<label for="autocomplete">Select your city address : </label>
<input id="autocomplete">
<input type="button" onclick="getResult()" value="Submit">
</body>
</html>
Right now as you see, when i click submit button the name on the input doesn't display either in the result div.
Upvotes: 0
Views: 981
Reputation: 26258
Try this:
Jquery:
$(document).ready(function(){
var projects = [
{
value: "1",
label: "jQuery"
},
{
value: "2",
label: "jQuery UI"
},
{
value: "3",
label: "Sizzle JS"
}
];
$( "#project" ).autocomplete({
minLength: 0,
source: projects,
focus: function( event, ui ) {
$( "#project" ).val( ui.item.label );
return false;
},
select: function( event, ui ) {
$( "#project" ).val( ui.item.label );
$( "#project-id" ).val( ui.item.value );
return false;
}
})
.autocomplete( "instance" )._renderItem = function( ul, item ) {
return $( "<li>" )
.append( "<div>" + item.label + "</div>" )
.appendTo( ul );
};
});
Html:
<div id="project-label">Select a project (type "j" for a start):</div>
<input id="project">
<input type="hidden" id="project-id">
This will give you id
in hidden
element.
Upvotes: 1