javascript - How do you JSON (instead of serialize) a form that has name="Item[][things]" without obtaining an object with null children? -
this pretty specific issue , can't find online or couldn't find solution until @ least.
i have form, contains inputs have: name = "item[][things]"
in item. can't change that. want turn json send server. can't use serialize, need turn json.
this doesn't work tried: json.stringify($myform.serializeobject())
. because form contains name="item[][differentotherthings]", array of nulls [null, null, ..., null]
i added serializeobject() custom method jquery-serialize-object project.
any ideas on how json form without null issue?
see bellow snippet
$(function(){ $("#serialize").click(function(){ var $myform = $("form").eq(0); var str = json.stringify($myform.serializeobject()); console.log(str); var object = json.parse(str); console.log(object); }) }); $.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; };
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form> <p><input type="text" name = "item[][things]"></p> <p><input type="text" name = "item[][things1]"></p> <p><input type="text" name = "item[][differentotherthings]"></p> </form> <button id="serialize">serialize</button>
Comments
Post a Comment