How to serialize a table into a json array so that each element of the array contains a json object representing one row of the table:
[ { name: "variable1", valuetostore: "ab", totaltype: "Lowest" }, { name: "variable2", valuetostore: "cd", totaltype: "Highest" } ]
I tried the code below, but this creates objects with name and value properties, and there are more elements in the array than in the rows of the table.
It also serializes the first line, which is hidden. This is a template string to add a string and should not contain the result.
$(function() { $("#btnShow").on("click", function() { console.log($("#myForm").serializeArray()); }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <div class="modal" id="reportVariables" tabindex="-1" role="dialog" aria-labelledby="reportVariablesLabel"> <div class="modal-dialog modal-lg" role="document"> <div class="modal-content"> <div class="modal-body"> <form id="myForm"> <table class="table table-condensed table-striped" id="reportVariablesTable"> <thead> <tr> <th>Name</th> <th>Value</th> <th>Calculate</th> </tr> </thead> <tbody> <tr style='display:none'> <td> <input type="text" name="name"> </td> <td> <textarea name="valuetostore"></textarea> </td> <td> <select class="totaltype-select" id="totaltype" name="totaltype"> <option value=""></option> <option value="Sum">Summary</option> <option value="Lowest">Smallest</option> <option value="Highest">Biggers</option> </select> </td> </tr> <tr> <td> <input type="text" name="name" value="variable1"> </td> <td> <textarea name="valuetostore">ab</textarea> </td> <td> <select class="totaltype-select" id="totaltype" name="totaltype"> <option value=""></option> <option value="Sum">Summary</option> <option value="Lowest" selected>Smallest</option> <option value="Highest">Biggers</option> </select> </td> </tr> <tr> <td> <input type="text" name="name" value="variable2"> </td> <td> <textarea name="valuetostore">cd</textarea> </td> <td> <select class="totaltype-select" id="totaltype" name="totaltype"> <option value=""></option> <option value="Sum">Summary</option> <option value="Lowest" >Smallest</option> <option value="Highest" selected>Biggers</option> </select> </td> </tr> </tbody> </table> <button id="btnShow" type="button"> Show </button> </form> </div> </div> </div> </div>
source share