Bind Cascading (Dependent) HTML Table using JSON in JavaScript

Last Reply 3 months ago By dharmendr

Posted 3 months ago

Hi!

I have two tables in html with json data. When I click button then show all data. Now I want separate second table data by cities.

When I click Tajikistan show all cities equal id 1.

When click Uzbekistan show all cities equal id 2 etc. 

<h3>
    Click the button to create a dynamic table using data extracted from a JSON array.
</h3>
<input type='button' onclick='countriesFromJson(), cityFromJson()' 
    value='Create Table from JSON data' />
<p id='showCountries'></p>
<p id='showCities'></p>

<script>
    function countriesFromJson() {
		// the json data. (you can change the values for output.)
        var myCountries = [
            {'ID': '1', 'Country': 'Tajikistan'
            },
            {'ID': '2', 'Country': 'Uzbekistan'
            },
            {'ID': '3', 'Country': 'Russia'
            }
        ]

        // Extract value from table header. 
        // ('ID', 'Country')
        var col = [];
        for (var i = 0; i < myCountries.length; i++) {
            for (var key in myCountries[i]) {
                if (col.indexOf(key) === -1) {
                    col.push(key);
                }
            }
        }

        // Create a table.
        var table = document.createElement("table");

        // Create table header row using the extracted headers above.
        var tr = table.insertRow(-1);                   // table row.

        for (var i = 0; i < col.length; i++) {
            var th = document.createElement("th");      // table header.
            th.innerHTML = col[i];
            tr.appendChild(th);
        }

        // add json data to the table as rows.
        for (var i = 0; i < myCountries.length; i++) {

            tr = table.insertRow(-1);

            for (var j = 0; j < col.length; j++) {
                var tabCell = tr.insertCell(-1);
                tabCell.innerHTML = myCountries[i][col[j]];
            }
        }

        // Now, add the newly created table with json data, to a container.
        var divShowCountries = document.getElementById('showCountries');
        divShowCountries.innerHTML = "";
        divShowCountries.appendChild(table);
    }    
  
     function cityFromJson() {
        // the json data. (you can change the values for output.)
        var myCities = [
            {'ID': '1', 'City': 'Dushanbe', 'CountryId':'1'
            },
            {'ID': '2', 'City': 'Khujand', 'CountryId':'1'
            },
            {'ID': '3', 'City': 'Bokhtar', 'CountryId':'1'
            },
            {'ID': '4', 'City': 'Toshkand', 'CountryId':'2'
            },
            {'ID': '5', 'City': 'Bukhoro', 'CountryId':'2'
            },
            {'ID': '6', 'City': 'Samarqand', 'CountryId':'2'
            },
            {'ID': '7', 'City': 'Kobul', 'CountryId':'3'
            },
            {'ID': '8', 'City': 'Qandahor', 'CountryId':'3'
            },
            {'ID': '9', 'City': 'Kunduz', 'CountryId':'3'
            }
        ]

        // Extract value from table header. 
        // ('ID', 'City', 'CountryId')
        var citycol = [];
        for (var i = 0; i < myCities.length; i++) {
            for (var key in myCities[i]) {
                if (citycol.indexOf(key) === -1) {
                    citycol.push(key);
                }
            }
        }

        // Create a table.
        var table = document.createElement("table");

        // Create table header row using the extracted headers above.
        var tr = table.insertRow(-1);                   // table row.

        for (var i = 0; i < citycol.length; i++) {
            var th = document.createElement("th");      // table header.
            th.innerHTML = citycol[i];
            tr.appendChild(th);
        }

        // add json data to the table as rows.
        for (var i = 0; i < myCities.length; i++) {

            tr = table.insertRow(-1);

            for (var j = 0; j < citycol.length; j++) {
                var tabCell = tr.insertCell(-1);
                tabCell.innerHTML = myCities[i][citycol[j]];
            }
        }

        // Now, add the newly created table with json data, to a container.
        var divShowCities = document.getElementById('showCities');
        divShowCities.innerHTML = "";
        divShowCities.appendChild(table);
    }
</script>

 

You are viewing reply posted by: dharmendr 3 months ago.
Posted 3 months ago

Hi PRA,

Check this example. Now please take its reference and correct your code.

HTML

<html>
<head>
    <meta charset="utf-8" />
    <title></title>
    <style>
        th, td, p, input, h3 {
            font: 15px 'Segoe UI';
        }

        table, th, td {
            border: solid 1px #ddd;
            border-collapse: collapse;
            padding: 2px 3px;
            text-align: center;
        }

        th {
            font-weight: bold;
        }
    </style>
</head>
<body>
    <h3>Click the button to create a dynamic table using data extracted from a JSON array.</h3>
    <input type='button' onclick='countriesFromJson(), cityFromJson("")' value='Create Table from JSON data' />
    <p id='showCountries'></p>
    <p id='showCities'></p>
    <script>
        function countriesFromJson() {
            var myCountries = [
                { 'ID': '1', 'Country': 'Tajikistan' },
                { 'ID': '2', 'Country': 'Uzbekistan' },
                { 'ID': '3', 'Country': 'Russia' }]
            var col = [];
            for (var i = 0; i < myCountries.length; i++) {
                for (var key in myCountries[i]) {
                    if (col.indexOf(key) === -1) {
                        col.push(key);
                    }
                }
            }
            var table = document.createElement("table");
            var tr = table.insertRow(-1);

            for (var i = 0; i < col.length; i++) {
                var th = document.createElement("th"); 
                th.innerHTML = col[i];
                tr.appendChild(th);
            }
            for (var i = 0; i < myCountries.length; i++) {

                tr = table.insertRow(-1);

                for (var j = 0; j < col.length; j++) {
                    var tabCell = tr.insertCell(-1);
                    tabCell.innerHTML = myCountries[i][col[j]];
                    tabCell.addEventListener("click", function (e) {
                        var countryId = e.currentTarget.parentNode.getElementsByTagName('TD')[0].innerHTML;
                        cityFromJson(countryId);
                    });
                }
            }
            var divShowCountries = document.getElementById('showCountries');
            divShowCountries.innerHTML = "";
            divShowCountries.appendChild(table);
        }

        function cityFromJson(country) {
            var myCities = [
                { 'ID': '1', 'City': 'Dushanbe', 'CountryId': '1' },
                { 'ID': '2', 'City': 'Khujand', 'CountryId': '1' },
                { 'ID': '3', 'City': 'Bokhtar', 'CountryId': '1' },
                { 'ID': '4', 'City': 'Toshkand', 'CountryId': '2' },
                { 'ID': '5', 'City': 'Bukhoro', 'CountryId': '2' },
                { 'ID': '6', 'City': 'Samarqand', 'CountryId': '2' },
                { 'ID': '7', 'City': 'Kobul', 'CountryId': '3' },
                { 'ID': '8', 'City': 'Qandahor', 'CountryId': '3' },
                { 'ID': '9', 'City': 'Kunduz', 'CountryId': '3' }]

            if (country != '') {
                var cities = [];
                myCities.filter(function (item) {
                    if (item.CountryId == country) {
                        cities.push(item);
                    }
                });

                myCities = cities;
            }

            var citycol = [];
            for (var i = 0; i < myCities.length; i++) {
                for (var key in myCities[i]) {
                    if (citycol.indexOf(key) === -1) {
                        citycol.push(key);
                    }
                }
            }

            var table = document.createElement("table");
            var tr = table.insertRow(-1);

            for (var i = 0; i < citycol.length; i++) {
                var th = document.createElement("th");
                th.innerHTML = citycol[i];
                tr.appendChild(th);
            }
            for (var i = 0; i < myCities.length; i++) {
                tr = table.insertRow(-1);
                for (var j = 0; j < citycol.length; j++) {
                    var tabCell = tr.insertCell(-1);
                    tabCell.innerHTML = myCities[i][citycol[j]];
                }
            }
            var divShowCities = document.getElementById('showCities');
            divShowCities.innerHTML = "";
            divShowCities.appendChild(table);
        }
    </script>
</body>
</html>

Demo