Is it possible when using jQuery's $.serialize()
or $.serializeArray()
to get the types of input fields (their attributes) that are being serialized? Obviously it sends the input names in the headers, but I'm wondering if I could grab like: textarea
, input type="text"
, input type="radio"
?
Asked
Active
Viewed 1,286 times
0

bob_cobb
- 2,229
- 11
- 49
- 109
-
get attributes to do what? combine with serialize? or store elsewhere? If combine.. what would you want structure to look like? – charlietfl Jun 23 '12 at 18:45
-
No, those APIs don't do that. You could write your own code to do it however, and then combine the parameter lists. – Pointy Jun 23 '12 at 18:47
-
@charlietfl I'd just want to get the attributes to store elsewhere essentially. Validate the fields in my model (while being POSTed to the controller) and somehow target the invalid fields (which I would be able to get by getting the attributes) and populate each of them with the error messages. – bob_cobb Jun 23 '12 at 18:52
2 Answers
1
How about this?
var allInputs = $("#myform *:input").map(function (i,e)
{
return {id: $(e).attr("id"),
name: $(e).attr("name"),
type: $(e).attr("type"),
tag: $(e).get(0).tagName
};
}
);
See http://jsfiddle.net/cranio/6uBLQ/
It gives an object with this form:
[{id: "c", name: "x" tag: "TEXTAREA" type: undefined},
{id: "a", name: "z", tag: "INPUT", type: "text"},
{id: "b", name: "y", tag: "INPUT", type: "hidden"},
...]
From that you could reference the inputs with their id, taking different actions based on tag and/or type, serialize and send this object, and so on. Works with hiddens, SELECTs, TEXTAREAs ...

Cranio
- 9,647
- 4
- 35
- 55
0
Can manipulate form input properties easily to any structure you want. Here's 2 flavors
DEMO: http://jsfiddle.net/zd3Pc/
/* array of element objects */
var formMap = $.map($('form :input'), function(el, idx) {
return {
type: el.type,
value: el.value,
name: el.name
};
});
/* object with arrays of name and value properties within type property */
var formObj = {}
$('form :input').each(function() {
if (!formObj[this.type]) {
formObj[this.type] = [];
}
formObj[this.type].push({
name: this.name,
value: this.value
})
})

charlietfl
- 170,828
- 13
- 121
- 150