javascript - Convert form fields into JSON object -
i have following form:
<form id="myform" method="post"> <input type="text" name="matrix[]" value="1"/><br/> <input type="text" name="matrix[]" value="2"/><br/> <input type="text" name="matrix[]" value="3"/><br/> <input type="text" name="multi_matrix[colors][]" value="red"/><br/> <input type="text" name="multi_matrix[colors][]" value="blue"/><br/> <input type="text" name="multi_matrix[weight][]" value="75"/><br/> <input type="text" name="multi_matrix[weight][]" value="83"/><br/> <input type="submit" value="send"> </form>
now want use javascript/jquery convert values json string. when use json.stringify($("#myform").serializearray()) code returns following:
[{"name":"matrix[]","value":"1"},{"name":"matrix[]","value":"2"},{"name":"matrix[]","value":"3"},{"name":"multi_matrix[colors][]","value":"red"},{"name":"multi_matrix[colors][]","value":"blue"},{"name":"multi_matrix[weight][]","value":"75"},{"name":"multi_matrix[weight][]","value":"83"}]
as can see fields have separate entry, want join them following:
{"matrix":[1,2,3],"multi_matrix":{"colors":["red","blue"],"weight":[75,83]}}
is there built-in function can ? or have iterate through fields , create json manually on own ?
you can extend jquery , create udf serializeobject done in this answer, based on serializearray():
$.fn.serializeobject = function() { var o = {}; var = this.serializearray(); $.each(a, function() { if (o[this.name] !== undefined) { 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; };
Comments
Post a Comment