0

I am trying to create a dynamic table using JavaScript. I need the table to take the form of a scheduler (hour blocks for 24 hours) It has to span a full 24 columns for the hours with a header for each block. 12am, 1am...11pm, etc. However, I'm currently restricted to the first col for the headers. My knowledge of JavaScript is at a beginner level. This is a basic representation of what I need and what is broken. What would be the best way to fix this code or implement something better?

function populateTable(table, time, rows, cells, content) {
            if (!table) table = document.createElement('table');
                var head = document.createElement('thead');
                var title = document.createElement('th');

                head.appendChild(title);
                    for (var x = 1; x <= time; x++){
                    table.appendChild(head);
                    title.appendChild(document.createTextNode(x));
                    }
                var body = document.createElement('tbody');
                    for (var i = 0; i < rows; ++i) {
                        var row = document.createElement('tr');
                            for (var j = 0; j < cells; ++j) {
                            row.appendChild(document.createElement('td'));
                            row.cells[j].appendChild(document.createTextNode(content + (j + 1)));
                            }
                        table.appendChild(row);
                    }
                return table;
                }
                $(document).ready(function () {
                    document.getElementById('scheduleTable')
                    .appendChild(populateTable(null,12,12, 12, "content"));
        });

1 Answer 1

1

Need to change the top part to:

var head = document.createElement('thead');
table.appendChild(head);

for (var x = 1; x <= time; x++) {
    var title = document.createElement('th');
    title.appendChild(document.createTextNode(x));
    head.appendChild(title);
}

If you want the title cells to be spread out correctly.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.