简体   繁体   中英

Converting user input from html table to JSON with jQuery

I am able to convert a pre populated table with data to JSON object with jQuery. Here is the code:

var header = $('table thead tr th').map(function () {
return $(this).text();
});

var tableObj = $('table tbody tr').map(function (i) {
    var row = {};
    $(this).find('td').each(function (i) {
        var rowName = header[i];
        row[rowName] = $(this).text();
    });
    return row;
}).get();

JSON.stringify(tableObj);

And the html table is like this:

<table>
        <thead>
        <tr>
            <th>Name</th>
            <th>E-mail</th>
            <th>Job</th>
        </tr>
        </thead>

        <tbody>
        <tr>
            <td>jason</td>
            <td>jason@example.com</td>
            <td>Developer</td>
        </tr>
        <tr>
            <td>ted</td>
            <td>ted@example.com</td>
            <td>Bear</td>
        </tr>
        </tbody>
</table>

Now my task is to actually handle empty table with user inputs. When user load the page, the table is empty with no value, after the user entered the input and click submit, I want to convert the user input data into JSON object and pass it back to back-end.

I am trying to make it happen by warp the table into a form , and add <input> tag in each <td> , something like this:

<form>
    <table>
        <tbody>
            <tr>
                <td><input type="text"/></td>
                <td><input type="text"/></td>
                <td><input type="text"/></td>
            </tr>
            <tr>
                <td><input type="text"/></td>
                <td><input type="text"/></td>
                <td><input type="text"/></td>
            </tr>
        </tbody>
    </table>
    <button type="submit">Submit</button>
</form>

I try to use the .submit() method from jQuery to make it work but I am getting syntax errors:

$('form').submit(
var header = $('table thead tr th').map(function () {
return $(this).text();
});

var tableObj = $('table tbody tr').map(function (i) {
    var row = {};
    $(this).find('td').each(function (i) {
        var rowName = header[i];
        row[rowName] = $(this).text();
    });
    return row;
}).get();

JSON.stringify(tableObj);
);

How should I change my code to make it work?

That's happening bacause there is no text in the td . You need to find the value of the input.

1) You need to get the input in the td

2) You need to get the value of the input

Also try to look at the editable div

Try this:

row[rowName] = $(this).find('input').val();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM