2016-12-26 20 views
0

我正在使用Twitter類型,但發現很難從mysql查詢中劃分結果。輸入提前血獵犬排序返回值。

我的JSON輸出看起來是這樣的:{「ID」:「1」,「名」:「布拉沃」}在當前狀態下

在預輸入結果顯示的名稱和ID,我會喜歡能夠僅顯示名稱,但輸入的實際提交值是id。我的腳本是流動的:

<script type="text/javascript"> 
// Instantiate the Bloodhound suggestion engine 
var suggestions = new Bloodhound({ 
    datumTokenizer: function (datum) { 
     return Bloodhound.tokenizers.whitespace(datum.value); 
    }, 
    queryTokenizer: Bloodhound.tokenizers.whitespace, 
    remote: { 
     url: 'includes/livesearch.php?key=%QUERY',  
     wildcard: '%QUERY', 
     filter: function (name) { 
      // Map the remote source JSON array to a JavaScript object array 
      return $.map(name, function (name) { 
       return { 
        value: name 
       }; 
      }); 
     } 
    } 
}); 
// Initialize the Bloodhound suggestion engine 
suggestions.initialize(); 

// Instantiate the Typeahead UI 
$('.typeahead').typeahead({ 
    hint: true, 
    minLength: 2 
}, { 
    limit: 7, 
    displayKey: 'value', 
    source: suggestions.ttAdapter(), 
}); 
</script> 

我非常歡迎任何幫助或建議。

謝謝!

回答

1

您可以創建一個對象來存儲當前檢索到的值。在filter選項Bloodhound將對象屬性設置爲name.name,並將值設置爲name.id

要返回並僅顯示name檢索到的屬性JSON,請使用參數$.map()檢查對象的屬性名稱。如果該物業是"name"返回{value:name},否則返回null

typeahead:selected使用事件中使用的.typeaheadinput的電流值作爲在filter初始返回值的先前存儲的對象中的屬性的參考來設置<form>內的<input type="hidden">元素的值。設置將值存儲到空對象的變量引用。

<form> 
    <input class="typeahead" type="text" placeholder="search"> 
    <input type="hidden" name="result" value="" /> 
    <input type="submit"> 
</form> 

$(function() { 
    // Instantiate the Bloodhound suggestion engine 
    var curr = {}; 
    var suggestions = new Bloodhound({ 
    datumTokenizer: function(datum) { 
     return Bloodhound.tokenizers.whitespace(datum.value); 
    }, 
    queryTokenizer: Bloodhound.tokenizers.whitespace, 
    remote: { 
     url: 'includes/livesearch.php?key=%QUERY',  
     wildcard: '%QUERY', 
     filter: function (name) { 
      curr[name.name] = name.id; 
      // Map the remote source JSON array to a JavaScript object array 
      return $.map(name, function (name, index) { 
       return index === "name" ? { 
        value: name 
       } : null; 
      }); 
     } 
    } 

    }); 
    // Initialize the Bloodhound suggestion engine 
    suggestions.initialize(); 

    // Instantiate the Typeahead UI 
    $(".typeahead").typeahead({ 
    hint: true, 
    minLength: 2 
    }, { 
    limit: 7, 
    displayKey: 'value', 
    source: suggestions.ttAdapter(), 
    }) 
    .on("typeahead:selected", function (e, datum) { 
    $("form [name=result]").val(curr[datum.value]); // set value here 
    curr = {}; 
    }); 
}) 

plnkr http://plnkr.co/edit/PJjzxemAQ9fO3P5YBfXi?p=preview

+0

作品完全相同的方式我所需要的!非常感謝你 ! –