Skip to content

Instantly share code, notes, and snippets.

@brettp
Created May 19, 2011 18:12
Show Gist options
  • Save brettp/981376 to your computer and use it in GitHub Desktop.
Save brettp/981376 to your computer and use it in GitHub Desktop.
Tabular json from table
/**
* Serializes inputs in a table to json preserving rows and cols
*
* Example:
* Doesn't work for multiple tables right now!
* var json = $('#table').toTabularJSON();
*
* If using inputs, think of each cell as an instance with limited scope. Use the same
* input names for consistency:
* <table>
* <tr>
* <td><input type="text" name="first_name" /></td>
* <td><input type="text" name="last_name" /></td>
* </tr>
* <tr>
* <td>
* <input type="text" name="first_name" />
* <input type="text" name="middle_initial" />
* </td>
* <td><input type="text" name="last_name" /></td>
* </tr>
* </table>
*
* Returns json like:
* [
* [ // tr
* [first_name: <value>], // td
* [last_name: <value>] // td
* ],
* [ // tr
* [ // td
* first_name: <value>,
* middle_initial: <value>
* ],
* [last_name: <value>] // td
* ]
* ]
*/
(function($) {
$.fn.toTabularJSON = function(opts) {
// default options
var defaults = {
onlyInputs: true
};
var options = $.extend(defaults, opts);
var json = [];
this.each(function() {
var table = [];
// find all the trs
var $tr = $('tr', this);
// find all the tds
$tr.each(function(trI, trE) {
var trData = [];
var $td = $('td', trE);
$td.each(function(tdI, tdE) {
var tdData = [];
if (options.onlyInputs) {
var input = $(':input', tdE);
input.each(function(iI, iE) {
$iE = $(iE);
tdData[$iE.attr('name')] = $iE.val();
});
} else {
tdData = $(tdE).html();
}
trData.push(tdData);
});
table.push(trData);
});
json.push(table);
});
return json;
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment