2016-05-08 21 views
0

我在我的html中使用Typeahead。我想顯示區域名稱並獲取區域ID。但我都顯示並獲得區域ID。如何解決它?Javascript - 在Typeahead中顯示名稱並獲取id

MYFILE,JS:

. 
. 
. 
var regions = response.data.result; 
console.log(regions); 

下面是結果的截圖在檢查元素: enter image description here

我想表明我的預輸入regionName並獲得regionId。

  var regionValue = regions.map(function(result) { 
       return result.regionId; 
      }); 
     $scope.autocomplete = $('.the-basics .typeahead').typeahead({ 
       hint: false, 
       highlight: false, 
       minLength: 1, 
       datumTokenizer: true 
      },{ 
       name: 'states', 
       source: substringMatcher(regionValue), 
       templates:{ 
        empty:[ 
         '<div class="empty-message"> No result...</div>' 
        ] 
       } 
      }) 


var substringMatcher = function(strs) { 
    return function findMatches(q, cb) { 
    var matches, substringRegex; 
    // an array that will be populated with substring matches 
    matches = []; 
    // regex used to determine if a string contains the substring `q` 
    substrRegex = new RegExp(q, 'i'); 
    // iterate through the pool of strings and for any string that 
    // contains the substring `q`, add it to the `matches` array 
    $.each(strs, function(i, str) { 
     if (substrRegex.test(str)) { 
     matches.push(str); 
     } 
    }); 
    cb(matches); 
    }; 
}; 

其實我想顯示regionName並得到regionId。任何建議?

回答

1

我知道你想要的是,在下拉regionName顯示,當你選擇的項目,你獲得的ID,如果是的話你可以做以下的只顯示regionName做到這一點

$scope.autocomplete = $('.the-basics .typeahead').typeahead({ 
      hint: false, 
      highlight: false, 
      minLength: 1, 
      datumTokenizer: true 
     },{ 
      name: 'states', 
      source: substringMatcher(regionValue), 
      templates:{ 
       empty:[ 
        '<div class="empty-message"> No result...</div>' 
       ], 
       suggestion: function(data) {  
         return '<p> + data.regionName + '</p>'; 
        } 
      } 
     }) 

和所選項目做呢

$('.the-basics .typeahead').bind('typeahead:selected', function(obj,datum, name) { 
    //put here you code after selected item 
    datum.regionId 
}) 

看那docs typeahead

時候才能元素的ID