jQuery create object from form fields
Solution 1
You can do this:
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...
Beware that forms can have fields with repeated names, and what you're trying to do doesn't support that. Also, the order of fields in HTML forms can be significant. (These are both reasons that serializeArray
works the way it does.)
Note that normal HTML practice is to omit disabled fields. If you want to do that, check this.disabled
before grabbing the value as well.
Note that the above (written two years ago) uses a jQuery pseudo-selector. I'm a bit surprised to find that I wrote that. As it says in the documentation for the :input
pseudo-selector, using it means that jQuery can't hand off the selector to the browser's native querySelectorAll
(which nearly all browsers now have).
Nowadays I'd probably write:
$("#theForm").find("input, textarea, select, button")...
...if I wanted buttons, or if not then
$("#theForm").find("input, textarea, select")...
...and then filter out input[type="button"]
and input[type="submit"]
inside the each
. E.g. (no buttons at all):
$("#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`...
}
});
Solution 2
var inputs = $("form :input");
var obj = $.map(inputs, function(x, y) {
return {
Key: x.name,
Value: $(x).val()
};
});
console.log(obj);
Solution 3
As per a comment on the http://api.jquery.com/serializeArray/ page, you can do:
(function( $ ){
$.fn.serializeJSON=function() {
var json = {};
jQuery.map($(this).serializeArray(), function(n, i){
json[n['name']] = n['value'];
});
return json;
};
})( jQuery );
Then do:
var obj = $('form').serializeJSON();
or if you need it with your fields
property, you can modify the function or do this:
var obj = {fields: $('form').serializeJSON()};
Or you can just use serializeArray()
if you don't mind that format of output.
Solution 4
Here is a simple solution:
$(".form-sample").serializeArray().map(function(x){data[x.name] = x.value;});
Solution 5
jquery has a serialize() function on froms like $('#myform').serialize()
is this what you're looking for?
update: oops, maybe try serializeArray() instead, it should give you an array of name and value.
Related videos on Youtube
Comments
-
Alex almost 2 years
How can I create a object with a form's fields and values?
like this one:
{ fields: { name: 'foo', email: '[email protected]', comment: 'wqeqwtwqtqwtqwet' } }
assuming the form looks like this:
<form> <input type="text" name="name" value="foo" /> <input type="text" name="email" value="[email protected]" /> <textarea name="comment">wqeqwtwqtqwtqwet</textarea> </form>
I need to know how can I do this for any form with a single function, not just a particular form.
-
Canuteson about 13 yearsWhat's the mission? What are you intending to do with this object?
-
Alex about 13 yearsi'm trying to create a ajax script that validates forms. and some fields depend on other fields, so I just send the entire object on any input change...
-
-
Slappy about 13 yearsneed to add the other form element types, but this is great
-
gion_13 about 13 yearsthere are also other elements to consider than input such as select, textarea
-
Hussein about 13 years
:input
works for all fields including textarea and select. I'm using:input
notinput
. see example jsfiddle.net/ASe4S -
Hussein about 13 yearsserialize does not give JSON output as OP requested
-
T.J. Crowder about 13 yearsThis doesn't produce the structure he asked for. This produces an array of objects, each with a single property based on the name of the field. Very difficult to use, he'd be better off using
serializeArray
as the property names (name
andvalue
) are defined (or, of course, something structured the way he did ask for, although that structure is limited as it doesn't support forms with repeated field names). -
albb about 13 years@Hussein Thanks, then maybe serializeArray() will work, I've updated my answer.
-
Hussein about 13 yearsCheck jsfiddle.net/ASe4S/1. Note serializearray does not work with disabled fields. map is a more flexible solution
-
Alex about 13 yearsthank you :P yes I need a fields property because I'm passing other properites too and don't want to confuse them
-
T.J. Crowder about 13 years@Hussein: "Note serializearray does not work with disabled fields"
serializeArray
works exactly correctly with disabled fields, according to the HTML specification. They are omitted, by design. But my issue wasn't with your usingmap
, it was with the original form of what you were creating. Your updated form is more useful, because at least the property names are defined, although it's still not what Alex asked for. -
Xerri almost 11 yearsYou might want to add .not("button") before .each since buttons are included as input fields
-
T.J. Crowder almost 11 years@thearchitect: Hence "The selector will match buttons; if you want to filter them out, check
this.tagName
andthis.type
; see below" :-) (Although I'm not seeing what "below" I was referring to!) I'm very surprised to see myself use a jQuery pseudo-selector in an answer, though. I guess it was two years ago... -
Xerri almost 11 yearshehe......there are some other details anyone using this needs to keep in mind. Radio buttons and checkboxes need to be catered for. I had to switch to using the id of a field instead of the name because of radio buttons. I think <select> is a special case as well.
-
internetross about 9 yearsPiggy-backing on @Xerri, another gotcha with radio buttons and checkboxes is that
.val()
won't give you the right thing - the value of these input types does not change whether it is checked or not. You want.prop('checked')
or a similar method to get the checked property value. -
Rutvij Kothari about 6 yearsThanks! Works like a charm when a form has an array. Perfect solution.