0

I have a JSON data like below :

[ { "id": 1 "name": "firstName" }, { "id": 2 "name": "secondName" } ]

Now, I am using Bootstrap Typeahead. I want to show the "name" to the users in typeahead dropdown, but I need the corresponding "id" of the "name" selected by the user what we used to do in select box. My requirement is something like these

<select>
   <option value="1">First Name</option>
   <option value="2">Second Name</option>
</select>
Siguza
  • 21,155
  • 6
  • 52
  • 89

1 Answers1

0

I'm not used to Bootstrap typeahead, but when I saw its examples after a little search, they're not showing off the data as a select menu. They're showing the data as div tags. So I don't think this is what you need.

So I'll share this jquery solution to create what you need from the data array that you've provided.

But first of all, your data array is an array of objects, so between the object element and the other one, there should be a comma "," , this is true except for the last element.

So your array should be like this :

[ { "id": 1, "name": "firstName" }, { "id": 2, "name": "secondName" } ]

And the jquery solution to write the select tag that you want from that array, is this :

var data=[ { "id": 1, "name": "firstName" }, { "id": 2, "name": "secondName" } ];
var el= document.createElement("select");
for (var i=0 ; i<data.length; i++){
    var child = "<option value='"+data[i].id+"'>"+data[i].name+"</option>";
    $(el).append(child);
}
document.body.appendChild(el); 

This is a fiddle for it.

BahaEddine Ayadi
  • 987
  • 9
  • 20