Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access values created by serializeArray in JQuery?

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()); 
like image 927
bart Avatar asked Nov 21 '10 06:11

bart


People also ask

What does serializeArray do in jQuery?

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.

What will you use in jQuery if you wanted to convert the contents of a form elements into string for submission?

You can do this: var frm = $(document. myform); var data = JSON. stringify(frm.


2 Answers

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']); 
like image 134
Jason Avatar answered Sep 18 '22 09:09

Jason


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.

like image 39
Nick Craver Avatar answered Sep 22 '22 09:09

Nick Craver