How to render a JSON response using the latest typeahead.js library

I have a search box in my application where users can search for patient data stored in a database. they will dial the patient’s name, and the server will respond to the JSON response with all the details. To facilitate this functionality, I use the latest version of typeahead.js.

Here is my javascript code:

$("#search-box").typeahead({ remote: 'searchPatient.do?q=%QUERY' }); 

This code gives me the following JSON response:

 [ { "id":1, "surname":"Daniel", "forename":"JOHN", "address": { "id":23, "houseNameOrNumber":"35", "addressDetail":"Roman House", "postCode":"NE1 2JS" }, "gender":"M", "age":27, "dateOfBirth":"25/08/1985" } ] 

When the typeahead library tries to display this answer, I always see undefined in the drop-down list. I want to show all the fields of this answer in the drop-down list of the automatic offer. I would appreciate it if anyone could help me.

I want to display an entry like this in the drop down list:

 John Daniel (M, 27) 35 Roman House, NE1 2JS 25/08/1985 

Thanks in advance!

+7
javascript jquery twitter-bootstrap bootstrap-typeahead
source share
1 answer

Your current code is too simple to achieve this, you need to use template and remote to achieve this:

 $('#search-box').typeahead([{ name: 'Search', valueKey: 'forename', remote: { url: 'searchPatient.do?q=%QUERY', filter: function (parsedResponse) { // parsedResponse is the array returned from your backend console.log(parsedResponse); // do whatever processing you need here return parsedResponse; } }, template: [ '<p class="name">{{forename}} {{surname}} ({{gender}} {{age}})</p>', '<p class="dob">{{dateOfBirth}}</p>' ].join(''), engine: Hogan // download and include http://twitter.imtqy.com/hogan.js/ }]); 

Just to give you a basic idea, hope this helps.

+7
source share

All Articles