Skip to content

table bulk editor #2

Description

@acivitillo

HTML tables can be used to send data in bulk back to the server for sql bulk loads via json. Here below is the prototype stimulus controller to turn a table into a json and post it to an api endpoint.

//https://j.hn/html-table-to-json/
import { Controller } from "stimulus"

export default class extends Controller {
    run() {
        var headers = [];
        var data = {}; // first row needs to be headers var headers = [];
        const table = document.getElementById("tablename")
        for (var i = 0; i < table.rows[0].cells.length; i++) {
            headers[i] = table.rows[0].cells[i].innerHTML.toLowerCase().replace(/ /gi, '');
        };
        // go through cells text_item
        for (var i = 1; i < table.rows.length; i++) {
            var tableRow = table.rows[i]; var rowData = {};
            for (var j = 0; j < tableRow.cells.length; j++) {
                for (var node of tableRow.cells[j].childNodes) {
                    if (node.nodeType == 1) {
                        if (node.innerHTML == "") {
                            switch (node.name) {
                                case "check":
                                    var value = node.checked
                                    break;
                                case "input_text":
                                    var value = node.value
                                    break;
                            };
                        } else {
                            var value = node.innerHTML
                        };
                    }
                };
                if (!(headers[j] in data)) {
                    data[headers[j]] = [];
                }
                data[headers[j]].push(value);
            }
        }
        const json = JSON.stringify({ item: data })
        fetch('/submit', {
            method: 'POST',
            headers: {
                "Content-Type": "application/json",
                "Accept": "application/json"
            },
            body: json
        });
        console.log(json);
        return data;
    };
}

Activity

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

Metadata

Metadata

Assignees

Labels

enhancementNew feature or request

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions