Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery-- Populate select from json

Tags:

jquery

I have a map in my java sevlet and converting it to a json format that works right.

When I do this function below it creates a drop down, but it puts every character as an option?? This is what I got:

$(document).ready(function(){     var temp= '${temp}';     //alert(options);     var $select = $('#down');                             $select.find('option').remove();                               $.each(temp, function(key, value) {                       $('<option>').val(key).text(value).appendTo($select);          }); }); 

map content in JSON format

{"1" : "string","2" : "string"} 
like image 346
Doc Holiday Avatar asked May 08 '13 13:05

Doc Holiday


People also ask

How to display json data in dropdownlist using JavaScript?

A pure Javascript solution: this snippet shows how to populate a dropdown select from JSON data (using id as value and name as text. The code creates a new Option object for each item in the JSON data and appends it to the select element with appendChild() . map is used in place of a for loop.

How do you populate the options of a select element in JavaScript?

createElement('select'); langArray. forEach((element, index) => { let option_elem = document. createElement('option'); // Add index to option_elem option_elem. value = index; // Add element HTML option_elem.


2 Answers

I would do something like this:

$.each(temp, function(key, value) {   $select.append(`<option value="${key}">${value}</option>`); }); 

JSON structure would be appreciated. At first you can experiment with find('element') - it depends on JSON.

like image 152
webrama.pl Avatar answered Sep 22 '22 07:09

webrama.pl


Only change the DOM once...

var listitems = ''; $.each(temp, function(key, value){     listitems += '<option value=' + key + '>' + value + '</option>'; }); $select.append(listitems); 
like image 32
cjrigdon Avatar answered Sep 21 '22 07:09

cjrigdon