【问题标题】:Get id and name on typehead在预先输入时获取 id 和 name
【发布时间】:2019-10-03 04:44:28
【问题描述】:

我可以返回姓名和 ID,但我只能打印姓名。

我尝试过更新和 sfterslected

目前我有这个代码并且工作正常,但我只是得到名字!

 $('input.typeahead').typeahead({
    source:  function (query, process) {
    return $.ajax({
    url: "search/autocomplete",
    type: "GET",
    data: "query=" + query,
    success: function(data) {

      var data = $.merge( $.merge( [], data['2'] ), data['1'] );
      return process(data); 
    }
    });

   }         
 });

得到的结果是得到它给出的名字和id(id应该打印在其他div例如#mydiv

提前致谢!

【问题讨论】:

    标签: javascript ajax typehead


    【解决方案1】:

    答案只是在选择之后添加

      $('input.typeahead').typeahead({
       source:  function (query, process) {
         return $.ajax({
         url: "search/autocomplete",
         type: "GET",
         data: "query=" + query,
         success: function(data) {
    
        var data = $.merge( $.merge( [], data['2'] ), data['1'] );
    
        return process(data); 
    
             // this returns an array checked with console
      }
    
    });
    
    },
     afterSelect: function(data){
        console.log(data.id);
    }
     });
    

    【讨论】:

      【解决方案2】:

      您可以使用 Bloodhound 为 typehead 制作指令

      app.directive('typeheadDirective', function() {
          return {
              restrict: 'A',
              scope: {
                  themes: '=',
                  output: '=',
              },
              link: function(scope, element, attrs) {
                  var themes = new Bloodhound({
                      datumTokenizer: Bloodhound.tokenizers.obj.whitespace('theme_name'),
                      queryTokenizer: Bloodhound.tokenizers.whitespace,
                      local: scope.themes,
                  })
                  element.typeahead(null, {
                      name: 'themes',
                      displayKey: function(item) {
                          return item.theme_name
                      },
                      source: themes.ttAdapter()
                  })
                  element.bind('typeahead:select', function(ev, theme) {
                      scope.output = {
                          'id': theme.id,
                          /*'theme_id': theme.id,*/
                          'theme_name': theme.theme_name
                      }
                      // element.value = ''
                      scope.$apply();
                  })
              }
          };
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-04-06
        • 1970-01-01
        • 2018-05-28
        • 1970-01-01
        • 2015-06-04
        • 1970-01-01
        • 2012-10-01
        • 1970-01-01
        相关资源
        最近更新 更多