I'd like to be able to create a javascript object from my html form and am wondering if there's a good way to do this using jquery. I guess what i'm looking for is something similar to $.serialize, but which would result in a map instead of a str开发者_运维百科ing.
<form>
<input type="text" name="foo1" value="bar1" />
<input type="text" name="foo2" value="bar2" />
</form>
desired result:
{ foo1:"bar1", foo2:"bar2" }
var oElements = {};
$('form [name]').each(function(){
oElements[this.name] = this.value;
});
Here is a much more robust take on the subject that uses jQuery. The extractObjectFromForm
takes a selector of the fields containing element and an arbitrary object instance. This works with known and unknown (grin) input types. It also can create complex object results that contain nested elements.
/**
* Extracts form elements and maps to passed in object
*/
function extractObjectFromForm($fieldContainer,objectType) {
var innerArray=[];
var obj = $.map($fieldContainer.find(":input"), function(n, i)
{
var o = {};
if($(n).is("input:text")
|| $(n).is("textarea")
|| $(n).is("input:hidden")
|| $(n).is("input:password"))
o[n.name] = $(n).val();
else if($(n).is("input:checkbox"))
o[n.name] = ($(n).is(":checked") ? true:false);
else if(n.type == 'radio') {
if(innerArray.indexOf(n.name)==-1) {
innerArray.push(n.name);
}
}
else
o[n.name] = $(n).val();
return o;
});
$.each(innerArray,function(index,item){
var iobj={};
iobj[item]=$("input[name='"+item+"']:checked").val();
obj.push(iobj);
});
return getObjectFromObject(obj,objectType);
}
/**
* Takes a object created from a form scour and
* converts it to an Object type
*/
function getObjectFromObject(formObject,outputObject) {
$.each(formObject,function(index,item){
$.each(item,function(key,value){
if(key.indexOf(".") == -1)
outputObject[key] = value;
else {
var mainkey = key.substr(0,key.indexOf("."));
var subkey = key.substr(key.indexOf(".")+1);
outputObject[mainkey][subkey]=value;
}
});
});
return outputObject;
}
How about serializeArray() http://api.jquery.com/serializeArray/
Update: Also found this plugin, which does essentially the same as the other poster's answer, but it looks like it can handle nested arrays. http://github.com/cowboy/jquery-misc/blob/master/jquery.ba-serializeobject.js
精彩评论