【问题标题】:Typeahead Bootstrap Return ID and Value JsonTypeahead Bootstrap 返回 ID 和值 Json
【发布时间】:2018-05-14 11:27:35
【问题描述】:

我需要预先输入的自动完成功能来处理名称字段,并且在单击项目时会收集 id 值。

$('.autocomplete').typeahead({
    source:  function (query, process) {
        return $.get('view/_list.php', { query: query }, function (data)
        {
            data = $.parseJSON(data);
            return process(data);
        });
    }
});

_list.php

[  

   {  
      "id":"47",
      "nome":"Maril\u00e2ndia"
   },
   {  
      "id":"57",
      "nome":"Pi\u00fama"
   },
   {  
      "id":"71",
      "nome":"Sooretama"
   }
]

仅当 json 没有 id,只有 name 字段时,自动完成才有效,但是如果您像在 json 示例中一样添加 name 字段,则没有任何效果。并且控制台中的错误是b.toLowerCase is not a function

【问题讨论】:

    标签: javascript php jquery json twitter-bootstrap


    【解决方案1】:

    您可以在对象上添加您希望的所有属性,只要 您提供“名称”属性或者您提供自己的 displayText 方法(source)。

    Here is the defaultText method:

    displayText: function (item) {
      return typeof item !== 'undefined' && typeof item.name != 'undefined' ? item.name : item;
    }
    

    因为你在_list.php的对象中有nome属性,而不是name属性,你需要设置displayText方法:

    $.get("_list.php", function(data){
        $(".autocomplete").typeahead({ source:data,
            displayText : function(item) {
                return item.nome;
            }
        });
    },'json');
    

    【讨论】:

      【解决方案2】:

      已解决。

      $('.autocomplet').typeahead({
        displayText: function(item) {
             return item.nome
        },
        afterSelect: function(item) {
              this.$element[0].value = item.nome;
              $("#field_id").val(item.id);
        },
        source: function (query, process) {
          return $.getJSON('_list.php', { query: query }, function(data) {
            process(data)
          })
        }   
      })
      

      【讨论】:

      • 您应该接受我或您的回答 (info)。
      猜你喜欢
      • 1970-01-01
      • 2015-10-16
      • 1970-01-01
      • 2018-06-23
      • 1970-01-01
      • 2013-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多