2017-03-29 123 views
0

[對不起,我不好英語]如何在JQuery UI Autocomplete中顯示名稱並獲取ID?

我想知道,如何從使用JQuery UI自動完成對象的數組得到ID
它顯示名稱。但是,當我點擊提交按鈕時,我想獲得id。

這是我一直在嘗試到目前爲止。

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>

現在你看,當我點擊提交按鈕的名稱輸入不無論是在結果DIV顯示。

+0

提供一個工作代碼小提琴? –

+0

您可以將上面的代碼複製到JSFiddle或運行代碼片段 –

+0

檢查我的答案 –

回答

1

試試這個:

的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"> 

這會給你idhidden元素。

Working Fiddle

相關問題