Skip to content

Instantly share code, notes, and snippets.

@redknitin
Last active August 23, 2018 12:54
Show Gist options
  • Save redknitin/a7cf26674822b86fa825222b925e55a9 to your computer and use it in GitHub Desktop.
Save redknitin/a7cf26674822b86fa825222b925e55a9 to your computer and use it in GitHub Desktop.
Javascript - Construct a table from an object array
<!doctype html><html>
<head>
<title></title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" type="text/css" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
<script>
var rows = []
function saveItem() {
f = document.getElementById('frm');
idx = f.elements["lineno"].value;
rec = {
'price': f.elements['price'].value,
'qty': f.elements['qty'].value,
'partcode': f.elements['partcode'].value
};
rows[idx] = rec;
f.elements["lineno"].value = rows.length; //next idx no
alert(rows.length);
loadData();
}
function clearTable() {
tabhead = document.getElementById('dtab').getElementsByTagName('thead')[0];
tabbody = document.getElementById('dtab').getElementsByTagName('tbody')[0];
for (i=tabhead.rows.length-1; i>=0; i--) {
tabhead.deleteRow(i);
}
for (i=tabbody.rows.length-1; i>=0; i--) {
tabbody.deleteRow(i);
}
}
function loadData() {
clearTable();
tabhead = document.getElementById('dtab').getElementsByTagName('thead')[0];
tabbody = document.getElementById('dtab').getElementsByTagName('tbody')[0];
is_first = true;
for (i=0; i<rows.length; i++) {
rec = rows[i];
newrow = tabbody.insertRow(tabbody.rows.length);
headrow = null;
for (var prop in rec) {
if (is_first) {
if (headrow == null)
headrow = tabhead.insertRow(tabhead.rows.length);
headcell = headrow.insertCell(0);
headcell.appendChild(document.createTextNode(prop));
}
newcell = newrow.insertCell(0);
newcell.appendChild(document.createTextNode(rec[prop]));
}
if (is_first) {
is_first = false;
}
}
}
</script>
</head>
<body>
<form method="get" action="" onsubmit="saveItem(); return false;" id="frm">
<input type="hidden" name="lineno" value="0" />
<div class="form-group">
<label></label>
<input class="form-control" name="partcode" value="a" />
</div>
<div class="form-group">
<label></label>
<input class="form-control" name="qty" value="1" />
</div>
<div class="form-group">
<label></label>
<input class="form-control" name="price" value="1" />
</div>
<input type="submit" />
</form>
<table id="dtab">
<thead></thead>
<tbody></tbody>
</table>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.3/modernizr.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
</body>
</html>
@redknitin
Copy link
Author

loadData can be re-used in other code:

//Example
/*
function preloadData() {
    headings = {
        'price': 'Price',
        'qty': 'Quantity',
        'partcode': 'Part Code',
    };
    data = [
        {'price': '13.75', 'qty': '1', 'partcode': 'ELE-001'},
        {'price': '10.25', 'qty': '2', 'partcode': 'ELE-002'},
        {'price': '1.00', 'qty': '12', 'partcode': 'ELE-003'},
        {'price': '0.75', 'qty': '8', 'partcode': 'ELE-004'},
        {'price': '45.00', 'qty': '6', 'partcode': 'ELE-005'},
    ];

    loadData('dtab', headings, data);
}

<table id="dtab" class="table">
<thead></thead>
<tbody></tbody>
</table>
*/


function clearTable() {
    tabhead = document.getElementById('dtab').getElementsByTagName('thead')[0];
    tabbody = document.getElementById('dtab').getElementsByTagName('tbody')[0];
    for (i=tabhead.rows.length-1; i>=0; i--) {
        tabhead.deleteRow(i);
    }
    for (i=tabbody.rows.length-1; i>=0; i--) {
        tabbody.deleteRow(i);
    }
}

function loadData(tableId, headings, data) {
    clearTable();

    tabhead = document.getElementById(tableId).getElementsByTagName('thead')[0];
    tabbody = document.getElementById(tableId).getElementsByTagName('tbody')[0];
    is_first = true;

    for (i=0; i<data.length; i++) {
        rec = data[i];
        newrow = tabbody.insertRow(tabbody.rows.length);
        headrow = null;
        for (var prop in rec) {
            if (is_first) {
                if (headrow == null)
                    headrow = tabhead.insertRow(tabhead.rows.length);
                headcell = headrow.insertCell(0);

                headcell.appendChild(document.createTextNode(headings[prop] || prop));
            }
            newcell = newrow.insertCell(0);
            newcell.appendChild(document.createTextNode(rec[prop]));
        }

        if (is_first) {
            is_first = false;
        }
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment