I am trying to convert data present in a HTML table into JSON so that it could be processed accordingly on the server side. I am able to serialize the data, but the results, at best, generate distinct arrays of data which aren't linked directly. Like: This is the form I am using:
<form id="nameGenderForm">
<table id="nameGenderTable">
<tr>
<th >Name</th>
<th >Gender</th>
</tr>
<tr>
<td><input type="text" name="studentName"></td>
<td>
<select name="studentGender">
<option value="male">male</option>
<option value="female">female</option>
</select>
</td>
</tr>
<tr>
<td><input type="text" name="studentName"></td>
<td>
<select name="studentGender">
<option value="male">male</option>
<option value="female">female</option>
</select>
</td>
</tr>
</table>
<input type="submit" />
</form>
The script to serialize the data is:
$("#nameGenderForm").submit(function(event){
event.preventDefault();
var rawData=$('#nameGenderForm').serializeFormJSON();
var formData=JSON.stringify(rawData);
console.log(formData);
});
serializeFormJSON() is what I got after going through few pages of StackOverFlow:
(function($) {
$.fn.serializeFormJSON = function() {
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
})(jQuery);
By using all these I am able to get a JSON something like this:
{"studentName":["kenpachi","orihime"],"studentGender":["male","female"]}
I tried many ways to get them in a name-gender format but every way yields the same result. Two distinct arrays. Using form for each didn't help either. Is there any way to get the data in name-gender array like this:
{"studentName":"kenpachi","studentGender":"male"},{"studentName":"orihime","studentGender":"female"}
Please advise.
Here you go with demo, made slight changes pointed below:
looped over each table row, and found input, textarea and select type elements, serialized them, converted to object and then pushed to an array.
var o = [];
$(this).find('tr').each(function() {
var $this = $(this);
var $elements = $this.find('input, textarea, select')
if ($elements.size() > 0) {
var serialized = $elements.serialize();
var item = $.toDictionary( serialized );
o.push(item);
}
});
P.S. added a new function to jquery library named toDictionary, so make sure you include that in your code as well.
$.toDictionary function
(function($) {
$.extend({
toDictionary: function(query) {
var parms = {};
var items = query.split("&"); // split
for (var i = 0; i < items.length; i++) {
var values = items[i].split("=");
var key = decodeURIComponent(values.shift());
var value = values.join("=")
parms[key] = decodeURIComponent(value);
}
return (parms);
}
})
})(jQuery);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With