I have this HTML:
<form id='myform'> <input name='title' value='foo'/> </form>
And I create an object array from it like this:
var dataArray = $("#myform").serializeArray();
Now how do I access 'title' in dataArray? This does not work:
alert(dataArray['title']); alert(dataArray['title'].val());
jQuery serializeArray() Method The serializeArray() method creates an array of objects (name and value) by serializing form values. You can select one or more form elements (like input and/or text area), or the form element itself.
You can do this: var frm = $(document. myform); var data = JSON. stringify(frm.
Similar to what Nick posted, but a little cleaner
var dataArray = $("#myform").serializeArray(), dataObj = {}; $(dataArray).each(function(i, field){ dataObj[field.name] = field.value; });
Then access the same way
alert(dataObj['title']);
You can either loop through, as @Tom has...or if you're accessing more than one, be a bit more efficient and loop once, creating an object like this:
var dataArray = $("#myform").serializeArray(), len = dataArray.length, dataObj = {}; for (i=0; i<len; i++) { dataObj[dataArray[i].name] = dataArray[i].value; }
Then you can access it like you want, for example:
alert(dataObj['title']); //or alert(dataObj.title);
You can test it out here.
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