Loading data into table from json file

  ajax, html, javascript, jquery, json

Section of my staffs.json file, there are multiple departments( Finance, HR, IT, marketing, sales, support)

{
    "staffs": [
        {
            "id": "100001",
            "firstName": "George",
            "lastName": "Facello",
            "department": "HR",
            "salary": 105000
        },
        {
            "id": "100002",
            "firstName": "Bella",
            "lastName": "Simmel",
            "department": "HR",
            "salary": 40000
        },

My HTML body:

<body>
    <h1>Staff List</h1>
    <div>
        Department:
        <label>
            <select name="comboBox" id="comboBox">
                <option value="finance">Finance</option>
                <option value="hr">HR</option>
                <option value="it">IT</option>
                <option value="marketing">Marketing</option>
                <option value="sales">Sales</option>
                <option value="support">Support</option>
            </select>
        </label>
    </div>
    <br>
    <div>Number of Staff:</div>
    <br>

    <table>
        <thead>
            <tr>
                <th>
                    ID
                </th>
                <th>
                    First Name
                </th>
                <th>
                    Last Name
                </th>
                <th>
                    Salary
                </th>
            </tr>
        </thead>

        <!-- Place holder for rows -->
        <tbody id="tablebody">

        </tbody>
    </table>
</body>

My script so far

<script>
        // global var
        let go = {};
        // entry point
        $(document).ready(main);
        function main(){
            log("Page is Loaded");

            // load json data async. using ajax + promise + arrow
            let option  = {url:"staffs.json", type:"GET", dataType:"json"};
            $.ajax(option).then(data =>
            {
                log("Success");

                // assign raw json data to global var
                go.json = data;

                // update staff data to the table
                updateStaff("finance");
            }).catch( () => log("Error loading JSON"));            
        }

        function updateStaff(order){
            log(order);
            let html = "";

            go.json.forEach((e,i) =>
            {
                log(i);
            })
        }
    </script>

I understand how to do something simpler like 1 column along with maybe a radioButton to swap. But I can’t figure out how to implement something like this. How to I add the correlating json data to each combobox department option?

Source: Ask Javascript Questions

LEAVE A COMMENT