super-user super-user - 2 months ago 8
JSON Question

Form Table Data to JSON string

I have a form that has a table with inputs and I need to properly convert it into json array per row. Example:

Id Name Gender
1 John Male
2 Rose Female

Desired output:
[
{ Id:1, Name: "John", Gender: "Male" },
{ Id:2, Name: "Rose", Gender: "Female" }
]


Please help me. I use this code

JSON.stringify($('#myform').serializeArray());


But it gives me this output:

[
{\"name\":\"Id\",\"value\":\"1\"},
{\"name\":\"Name\",\"value\":\"John\"},
{\"name\":\"Gender\",\"value\":\"Male\"}
]


See it in action: https://jsfiddle.net/srssnzj8/2/

Answer

To do what you require you can use map() to create an array of the values of the input and select elements within each tr. Try this:

$(document).on('click', '#save', function(event) {
    event.preventDefault();
    var data = $('tr').map(function() {
    	var obj = {};
    	$(this).find('input, select').each(function() {
        	obj[this.name] = $(this).val();
        });
        return obj;
    }).get();
    
    console.log(JSON.stringify(data));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<form method="post" action="#" id="myForm">
    <table>
        <tr>
            <td>
                <span>1</span>
                <input type="hidden" name="Id" value="1" />
            </td>
            <td>
                <input type="text" name="Name" value="John" />
            </td>
            <td>
                <select class="form-control" name="Gender">
                    <option value="Male" selected>Male</option>
                    <option value="Female">Female</option>
                </select>
            </td>
        </tr>
        <tr>
            <td>
                <span>2</span>
                <input type="hidden" name="Id" value="2" />
            </td>
            <td>
                <input type="text" name="Name" value="Rose" />
            </td>
            <td>
                <select class="form-control" name="Gender">
                    <option value="Male">Male</option>
                    <option value="Female" selected>Female</option>
                </select>
            </td>
        </tr>
    </table>
    <button type="submit" id="save">
        Submit
    </button>
</form>

Comments