使用javascript自动完成功能显示的城市名称

时间:2017-12-22 06:36:08

标签: javascript jquery arrays node.js mongodb

代码:

 $.ajax({
        url : '/Addbus',
        type : 'POST',
        dataType : 'JSON',
        success : function(data){
        var dt = JSON.parse(data.body);
            $.each(dt,function(i,v){
               $.each(v,function(j,p){
             var arr={};
                 arr= p.name+ ',' +p.id;
                temp.push(arr);
            var result=JSON.stringify(temp);
         console.log(result);

      $("#source").autocomplete({
        source: result, // The source of the AJAX results
        minLength: 3, // The minimum amount of characters that must be typed before the autocomplete is triggered
        focus: function( event, ui ) { // What happens when an autocomplete result is focused on
            $("#source").val( ui.item.value );
            return false;
      },
      select: function ( event, ui ) { // What happens when an autocomplete result is selected
          $("#source").val( ui.item.value );
          $('#source-id').val( ui.item.label );
      }
  });

当我在文本框中选择cityname然后在ui.item.valueui.item.label中我将值设为 项目 : 标签 : "海得拉巴,6" 值 : "海得拉巴,6&#34 ;, 现在我如何分离它们并采用不同的值。例如我希望值为id = 6和name = hyderabad。

3 个答案:

答案 0 :(得分:2)

const name = ui.item.value.split(',')[0];
const id = ui.item.value.split(',')[1];

答案 1 :(得分:0)

也许这会对你有帮助,不要对结果数组进行字符串化,将其用作源代码中的数组

$.ajax({
        url : '/Addbus',
        type : 'POST',
        dataType : 'JSON',
        success : function(data){
        var dt = JSON.parse(data.body);
            $.each(dt,function(i,v){
               $.each(v,function(j,p){
             var arr={};
                 arr.label = p.name;
                 arr.value = p.id;
                temp.push(arr);
            var result=temp

      $("#source").autocomplete({
        source: result, // The source of the AJAX results
        minLength: 3, // The minimum amount of characters that must be typed before the autocomplete is triggered
        focus: function( event, ui ) { // What happens when an autocomplete result is focused on
            $("#source").val( ui.item.value );
            return false;
      },
      select: function ( event, ui ) { // What happens when an autocomplete result is selected
          $("#source").val( ui.item.value );
          $('#source-id').val( ui.item.label );
      }
  });

答案 2 :(得分:0)

尝试使用这个......

const name = ui.item.split(',')[0];

const id = ui.item.split(',')[1];