如何显示名称&在JQuery UI Autocomplete中获取id?

时间:2017-03-29 05:12:24

标签: javascript jquery jquery-ui autocomplete

[抱歉,我的英语不好]

我想知道,如何使用JQuery UI Autocomplete从对象数组中获取 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中。

1 个答案:

答案 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">

这会在id元素中为您提供hidden

http://www.chartjs.org/docs/#chart-configuration-legend-configuration