Search code examples
javascripthtmlformshtml-tableinnerhtml

Convert form input fields of an HTML table to JSON


I'm currently learning javascript and as an exercice I'm trying to convert an HTML form table to JSON, send it over a communication interface and adding it to another page.

I'm currently able to parse the content of most fields by running through the table with the following code.

function tableToJson(table)
{
    var data = [];

    var headers = [];
    for(var i=0; i<table.rows[0].cells.length; i++)
    {
        headers[i] = table.rows[0].cells[i].innerHTML.toLowerCase();
    }

    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++)
        {
            rowData[ headers[j] ] = tableRow.cells[j].innerHTML;
        }
        data.push(rowData);
    }

    return JSON.stringify(data);
}

var tables = document.getElementsByTagName("table");

if(tables.length > 0)
{
    var json = tableToJson(tables[0]);
    console.log(json);
    /* Send part bellow */
}

I'm also able to send it through communication once it has been converted and to reimplement it into a new popup from the received JSON.

The problem I'm facing is when some of the fields are input tags with pre-filled values as follow.

<td style="width: 8%; vertical-align: middle; border-top: 1px solid rgba(56, 103, 214, 0.2);">
    <input type="number" step="0.01" name="form[18046][amount]" class="form-control">
</td>

The value is not directly available into the cell's innerHTML so the converted JSON data contains the HTML code but not the pre-filled value so when I reimplement the table on the new popup, I have an empty input field.

I would like to be able to get the prefilled value from the innerHTML so I can get rid of the input tag to keep only the value.

Maybe the best way would be to access the value form[18046][amount] through the DOM but I can't find a way to do it.

Does somebody knows how I could get the input prefilled value instead of the cell's innerHTML ?


Solution

  • I've been able to get the pre-filled value by parsing the innerHTML string to retrieve the 'name' attribute value and to ask the DOM the associated value.

    var name = tableRow.cells[j].innerHTML.replace(/.*name="([^"]+)".*$/g, "$1");
    rowData[headers[j]] = document.getElementsByName(name)[0].value;
    

    I'm still oppened to any other solution, I feel like this ain't the best one at all.