Search code examples
javascripthtmljsondropdownbox

How to populate div tables and dropdownboxes with JSON and Javascript?


I've been trying to populate div tables with dummy JSON data but I cannot seem to do it. What I want to do is display certain data depending of the selection in a dropdownbox. Also I need to create new row with a new dropdownbox when an item is selected. Could you give me some advice of what's the best way to do it. I'm able to create something close to what I need in Angular but I need it in pure JavaScript. Thanks in advance!

structure of my div tables


Solution

  • Suppose in data you have json object

    var data = [
    {
      "line": "Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.",
      "author": "Brian W. Kernighan",
      "num" : ["1","2","3"]
    },
    {
      "line": "Walking on water and developing software from a specification are easy if both are frozen.",
      "author": "Edward V Berard",
      "num" : ["5","0","15"]
    },
    {
      "line": "It always takes longer than you expect, even when you take into account Hofstadter's Law.",
      "author": "Hofstadter's Law",
      "num" : ["15","222","301"]
    }];
    

    and you want to populate all authors in above json object to table and num into respective dropdown element of table-row. Then following populateHTML() function populate object to table and num into respective dropdown element of table-row as shown in below image .enter image description here

    function populateHTML(data) {    
        if (typeof(data) == 'object') {
            document.write('<table>');
            for (var i in data) {
                document.write('<tr><td>'+data[i].author+'</td><td><select>');
                for(var j in data[i].num){
                     document.write('<option>' +data[i].num[j]+ '</option>');  
                }
                document.write('</select></td></tr>'); 
            }
            document.write('</tr></table>');
        } else {
            document.write(' => ' + data);
        }
    }