Reputation: 1480
Working on bootstrap typehead for autocomplete. With the help of the typehead documentation the autocomplete working fine but when I select the particular value from autocomplete i need to get the relevant name in the label field.
This is my HTML code.
<input type="text" class="ipt_Field" id="txt_schName" name="txt_schName" />
<label id="school_Name"></label>
This is my json data
["COL000001,Emirates College of Technology- UAE","COL000002,Al Khawarizmi International College- UAE","COL000003,Syscoms College","COL000004,Abounajm Khanj Pre-Uni Center","COL000005,Advanced Placement","COL000006,Al Buraimi College (Uni Clge)","COL000007,Al-Ain Community College","COL000008,AMA Computer College","COL000009,Arab Academy for Bankg and Fin","COL0000010,ARABACDSCITECHMARTIMETRNS","COL0000011,Arapahoe Community College"]
This is my jquery code
$("#txt_schName").typeahead({
name: 'School Name',
// data source
prefetch: 'json/school_name.json',
// max item numbers list in the dropdown
limit: 5,
minLength:3
});
Kindly please guide me how to get the corresponding vaule to the label. I am struggling lot.
Thanks & Regards Mahadevan
Upvotes: 0
Views: 401
Reputation: 2923
To keep a simple key / value pair, split-up your data into an array of objects. For example:
var aData = [{
"iso": "DE",
"desc" : "Germany"
}, {
"iso": "FR",
"desc" : "France"
}, {
"iso": "CA",
"desc" : "Canada"
}, {
"iso": "NO",
"desc" : "Norway"
}];
Configure your typeahead.js as follows
$(function () {
var bhData = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace("desc"),
queryTokenizer: Bloodhound.tokenizers.whitespace,
local: aData
});
$('.typeahead').typeahead(null, {
name: 'countrylist',
display: 'desc',
limit: 50,
source: bhData,
templates: {
empty: ['<div class="empty-message">', 'unable to find country', '</div>'].join('\n'),
suggestion: function (data) {
return '<p><strong>' + data.iso + '</strong> ' + data.desc + '</p>';
}
}
});
// Capture selected event and output the selected key / value data
$('.typeahead').on('typeahead:selected', function (event, data) {
$("#iso").html( data.iso );
$("#desc").html( data.desc );
});
});
Here's a link to a full working example https://jsfiddle.net/W_Walseth/uL4Lkmdt/4/
Upvotes: 1