jQuery create object from form fields

42,445

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:

See Demo

$(".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.

Share:
42,445

Related videos on Youtube

Alex
Author by

Alex

I'm still learning so I'm only here to ask questions :P

Updated on July 09, 2022

Comments

  • Alex
    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
      Canuteson about 13 years
      What's the mission? What are you intending to do with this object?
    • Alex
      Alex about 13 years
      i'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
    Slappy about 13 years
    need to add the other form element types, but this is great
  • gion_13
    gion_13 about 13 years
    there are also other elements to consider than input such as select, textarea
  • Hussein
    Hussein about 13 years
    :input works for all fields including textarea and select. I'm using :input not input. see example jsfiddle.net/ASe4S
  • Hussein
    Hussein about 13 years
    serialize does not give JSON output as OP requested
  • T.J. Crowder
    T.J. Crowder about 13 years
    This 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 and value) 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
    albb about 13 years
    @Hussein Thanks, then maybe serializeArray() will work, I've updated my answer.
  • Hussein
    Hussein about 13 years
    Check jsfiddle.net/ASe4S/1. Note serializearray does not work with disabled fields. map is a more flexible solution
  • Alex
    Alex about 13 years
    thank 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
    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 using map, 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
    Xerri almost 11 years
    You might want to add .not("button") before .each since buttons are included as input fields
  • T.J. Crowder
    T.J. Crowder almost 11 years
    @thearchitect: Hence "The selector will match buttons; if you want to filter them out, check this.tagName and this.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
    Xerri almost 11 years
    hehe......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
    internetross about 9 years
    Piggy-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
    Rutvij Kothari about 6 years
    Thanks! Works like a charm when a form has an array. Perfect solution.