How to create an HTML selection option from a JSON hash?

I have a simple JSON code:

[{'1':'Name'}, {'2', 'Age'}, {'3','Gender'}] 

I have a select tag in my HTML:

 <select name="datas" id="datas"></select> 

I need an easy way to create a window to select HTML from this JSON, for example:

 <select name="datas" id="datas"> <option value="1">Name</option> <option value="2">Age</option> <option value="3">Gender</option> </select> 
+4
source share
3 answers

Just for kicks here the answer is in pure javascript, also you probably don't need an array, a simple object is enough for this

  <select name="datas" id="datas"></select> <script> html = ""; obj = { "1" : "Name", "2": "Age", "3" : "Gender" } for(var key in obj) { html += "<option value=" + key + ">" +obj[key] + "</option>" } document.getElementById("datas").innerHTML = html; </script> 
+6
source

Try it.

 //Correct(missing colons) in the array items var data = [{'1':'Name'}, {'2': 'Age'}, {'3': 'Gender'}]; 

Create an option element, and then use the append method to add them to the select element.

 var $select = $('#datas'); $.each(data, function(i, val){ $select.append($('<option />', { value: (i+1), text: val[i+1] })); }); 

Demo

+7
source

The answer above assumes that the data indices of the array are ordered. What if the data variable is:

 var data = [ {'23':'Age'}, {'12':'Gender'}, {'3':'Name'}]; 

So, in alphabetical order, but with random identifiers.

One way to find this:

 $.each(data, function(key, value) { var i = Object.keys(value)[0]; $("select#datas").append( $("<option />").val(i).text(value[i]) ); 
+1
source

Source: https://habr.com/ru/post/1393860/


All Articles