Usted puede hacer esto:
var fields = {};
$("#theForm").find(":input").each(function() {
// The selector will match buttons; if you want to filter
// them out, check `this.tagName` and `this.type`; see
// below
fields[this.name] = $(this).val();
});
var obj = {fields: fields}; // You said you wanted an object with a `fields` property, so...
Tenga en cuenta que las formas pueden tener campos con nombres repetidos, y lo que estás tratando de hacer no lo respalda. Además, el pedido de campos en formularios HTML puede ser significativo. (Estas son las dos razones por las que serializeArray
funciona de la forma en que lo hace.)
Tenga en cuenta que la práctica normal de HTML es omitir los campos deshabilitados. Si desea hacerlo, marque this.disabled
antes de obtener el valor también.
Tenga en cuenta que lo anterior (escrito hace dos años) utiliza un pseudo-selector jQuery. Estoy un poco sorprendido de encontrar que escribí eso. Como dice en el documentation for the :input
pseudo-selector, usarlo significa que jQuery no puede transferir el selector al querySelectorAll
nativo del navegador (que casi todos los navegadores tienen ahora).
Hoy en día probablemente me escribe:
$("#theForm").find("input, textarea, select, button")...
... si quería botones, o si no, entonces
$("#theForm").find("input, textarea, select")...
... y luego filtrar a cabo input[type="button"]
y input[type="submit"]
dentro del each
. P.ej.(No hay botones en absoluto):
$("#theForm").find("input, textarea, select").each(function() {
var inputType = this.tagName.toUpperCase() === "INPUT" && this.type.toUpperCase();
if (inputType !== "BUTTON" && inputType !== "SUBMIT") {
// ...include it, either it's an `input` with a different `type`
// or it's a `textarea` or a `select`...
}
});
¿Cuál es la misión? ¿Qué piensas hacer con este objeto? – Canuteson
Estoy tratando de crear un script ajax que valide formularios. y algunos campos dependen de otros campos, así que solo envío el objeto completo en cualquier cambio de entrada ... – Alex