ChatGPT解决这个技术问题 Extra ChatGPT

How can I get form data with JavaScript/jQuery?

Is there a simple, one-line way to get the data of a form as it would be if it was to be submitted in the classic HTML-only way?

For example:

<form>
    <input type="radio" name="foo" value="1" checked="checked" />
    <input type="radio" name="foo" value="0" />
    <input name="bar" value="xxx" />
    <select name="this">
        <option value="hi" selected="selected">Hi</option>
        <option value="ho">Ho</option>
</form>

Output:

{
    "foo": "1",
    "bar": "xxx",
    "this": "hi"
}

Something like this is too simple, since it does not (correctly) include textareas, selects, radio buttons and checkboxes:

$("#form input").each(function () {
    data[theFieldName] = theFieldValue;
});
Another question similar to this: stackoverflow.com/questions/169506/…

h
hexacyanide

Use $('form').serializeArray(), which returns an array:

[
  {"name":"foo","value":"1"},
  {"name":"bar","value":"xxx"},
  {"name":"this","value":"hi"}
]

Other option is $('form').serialize(), which returns a string:

"foo=1&bar=xxx&this=hi"

Take a look at this jsfiddle demo


serializeArray would be so much more useful if it returned an object with key-value pairs
I agree that an object would be ideal. However, there is a problem - a key is allowed to have multiple values. Would you return a key-"array of values" object, or key-"first value" or something else? I think jQuery guys chose none of the above :)
Be aware of a problem with multiple values (as @Paul mentioned above), checkboxes and multiple inputs with name="multiple[]" do not work. The solution for POST method is the same, just use $('form').serialize(). Also the POST method does not have limit of 2000 characters as GET does in most browsers, so can be used even for a pretty large data.
Please also beware that in order to record a value from any form input, the input must have a name attribute.
@GetFree why not just use the jQuery map function? function getFormData(form) { var rawJson = form.serializeArray(); var model = {}; $.map(rawJson, function (n, i) { model[n['name']] = n['value']; }); return model; }
c
chelmertz
$('form').serialize() //this produces: "foo=1&bar=xxx&this=hi"

demo


Close, but perhaps something that returns an array with key-value pairs instead of a single string?
Nvm, found it in the comments for the serialize() function. It's called serializeArray. It returns an array of arrays (which contain an entry "name" and "value") but that should be easy enough to transform.
And using underscore library can be transformed using: _.object($("#myform").serializeArray().map(function(v) {return [v.name, v.value];} ))
@BartvanHeukelom I know this is 4 years later, but .serializeArray() will return an array.
m
mikemaccana

Updated answer for 2014: HTML5 FormData does this

var formData = new FormData(document.querySelector('form'))

You can then post formData exactly as it is - it contains all names and values used in the form.


Plus one as FormData is good and useful, but worth noting that if you want to READ the data inside FormData it's not quite so easy (see stackoverflow.com/questions/7752188/…)
@StackExchangeWhatTheHeck What do you mean? formData.get('something')
@brad That comment is from eight years ago. .get() used to not exist.
n
neuront

Based on jQuery.serializeArray, returns key-value pairs.

var data = $('#form').serializeArray().reduce(function(obj, item) {
    obj[item.name] = item.value;
    return obj;
}, {});

Key-value pairs here, guys, everybody, come here! It is golden!!! Thanks! If I want a value of an element named "retailer", I do this console.log($('#form').serializeArray().reduce(function(obj, item) { obj[item.name] = item.value; return obj;}, {} )['retailer']);
B
Brad
document.querySelector('form').addEventListener('submit', (e) => {
  const formData = new FormData(e.target);
  // Now you can use formData.get('foo'), for example.
  // Don't forget e.preventDefault() if you want to stop normal form .submission
});

This is a nitpicky answer, but let me explain why this is a better solution:

We're properly handling a form submit rather than a button press. Some people like to push enter on fields. Some people use alternative input devices such as speech input or other accessibility devices. Handle the form submit and you correctly solve it for everyone.

We're digging into the form data for the actual form that was submitted. If you change your form selector later, you don't have to change the selectors for all the fields. Furthermore, you might have several forms with the same input names. No need to disambiguate with excessive IDs and what not, just track the inputs based on the form that was submitted. This also enables you to use a single event handler for multiple forms if that is appropriate for your situation.

The FormData interface is fairly new, but is well supported by browsers. It's a great way to build that data collection to get the real values of what's in the form. Without it, you're going to have to loop through all the elements (such as with form.elements) and figure out what's checked, what isn't, what the values are, etc. Totally possible if you need old browser support, but the FormData interface is simpler.

I'm using ES6 here... not a requirement by any means, so change it back to be ES5 compatible if you need old browser support.


f
fringd

It is 2019 and there's a better way to do this:

const form = document.querySelector('form');
const data = new URLSearchParams(new FormData(form).entries());

or if you want a plain Object instead

const form = document.querySelector('form');
const data = Object.fromEntries(new FormData(form).entries());

although note that this won't work with duplicate keys like you get from multi-select and duplicate checkboxes with the same name.


G
Guilherme Iazzetta

Simplest way, 2022.

document.querySelector('form').addEventListener('submit', (e) => {
  const data = Object.fromEntries(new FormData(e.target).entries());
  console.log(data)
});

Output

{ name: 'Stackoverflow' }

Yep! Js is still not a developer friendly language in 2021 in my mind~ Why not just e.target.toJson()~
N
Nils

use .serializeArray() to get the data in array format and then convert it into an object:

function getFormObj(formId) {
    var formObj = {};
    var inputs = $('#'+formId).serializeArray();
    $.each(inputs, function (i, input) {
        formObj[input.name] = input.value;
    });
    return formObj;
}

C
Clox

Here's a really simple and short soluton that even doesn't require Jquery.

var formElements=document.getElementById("myForm").elements;    
var postData={};
for (var i=0; i<formElements.length; i++)
    if (formElements[i].type!="submit")//we dont want to include the submit-buttom
        postData[formElements[i].name]=formElements[i].value;

This doesn't work with radio buttons: the last option is always the one stored to postData.
M
Milli

I use this:

jQuery Plugin

(function($){
  $.fn.getFormData = function(){
    var data = {};
    var dataArray = $(this).serializeArray();
    for(var i=0;i<dataArray.length;i++){
      data[dataArray[i].name] = dataArray[i].value;
    }
    return data;
  }
})(jQuery);

HTML Form

<form id='myform'>
  <input name='myVar1' />
  <input name='myVar2' />
</form>

Get the Data

var myData = $("#myForm").getFormData();

Just a note that a year later I now think this is a terrible answer and no one should use it. As the previous comment says, things like radio buttons would not work. There are better answers above, use one of those instead.
p
pixeline
$("#form input, #form select, #form textarea").each(function() {
 data[theFieldName] = theFieldValue;
});

other than that, you might want to look at serialize();


K
Kyle Falconer

Here is a working JavaScript only implementation which correctly handles checkboxes, radio buttons, and sliders (probably other input types as well, but I've only tested these).

function setOrPush(target, val) {
    var result = val;
    if (target) {
        result = [target];
        result.push(val);
    }
    return result;
}

function getFormResults(formElement) {
    var formElements = formElement.elements;
    var formParams = {};
    var i = 0;
    var elem = null;
    for (i = 0; i < formElements.length; i += 1) {
        elem = formElements[i];
        switch (elem.type) {
            case 'submit':
                break;
            case 'radio':
                if (elem.checked) {
                    formParams[elem.name] = elem.value;
                }
                break;
            case 'checkbox':
                if (elem.checked) {
                    formParams[elem.name] = setOrPush(formParams[elem.name], elem.value);
                }
                break;
            default:
                formParams[elem.name] = setOrPush(formParams[elem.name], elem.value);
        }
    }
    return formParams;
}

Working example:

function setOrPush(target, val) { var result = val; if (target) { result = [target]; result.push(val); } return result; } function getFormResults(formElement) { var formElements = formElement.elements; var formParams = {}; var i = 0; var elem = null; for (i = 0; i < formElements.length; i += 1) { elem = formElements[i]; switch (elem.type) { case 'submit': break; case 'radio': if (elem.checked) { formParams[elem.name] = elem.value; } break; case 'checkbox': if (elem.checked) { formParams[elem.name] = setOrPush(formParams[elem.name], elem.value); } break; default: formParams[elem.name] = setOrPush(formParams[elem.name], elem.value); } } return formParams; } // // Boilerplate for running the snippet/form // function ok() { var params = getFormResults(document.getElementById('main_form')); document.getElementById('results_wrapper').innerHTML = JSON.stringify(params, null, ' '); } (function() { var main_form = document.getElementById('main_form'); main_form.addEventListener('submit', function(event) { event.preventDefault(); ok(); }, false); })();

what is a?

A and/or B?

edit:

If you're looking for a more complete implementation, then take a look at this section of the project I made this for. I'll update this question eventually with the complete solution I came up with, but maybe this will be helpful to someone.


T
Tom McDonough

I have included the answer to also give back the object required.

function getFormData(form) {
var rawJson = form.serializeArray();
var model = {};

$.map(rawJson, function (n, i) {
    model[n['name']] = n['value'];
});

return model;
}

This won't handle arrays at all; foo[bar][] = 'qux' should serialize to { foo: { bar: [ 'qux' ] } }.
R
RobKohr

If you are using jQuery, here is a little function that will do what you are looking for.

First, add an ID to your form (unless it is the only form on the page, then you can just use 'form' as the dom query)

<form id="some-form">
 <input type="radio" name="foo" value="1" checked="checked" />
 <input type="radio" name="foo" value="0" />
 <input name="bar" value="xxx" />
 <select name="this">
  <option value="hi" selected="selected">Hi</option>
  <option value="ho">Ho</option>
</form>

<script>
//read in a form's data and convert it to a key:value object
function getFormData(dom_query){
    var out = {};
    var s_data = $(dom_query).serializeArray();
    //transform into simple data/value object
    for(var i = 0; i<s_data.length; i++){
        var record = s_data[i];
        out[record.name] = record.value;
    }
    return out;
}

console.log(getFormData('#some-form'));
</script>

The output would look like:

{
 "foo": "1",
 "bar": "xxx",
 "this": "hi"
}

J
José Manuel Blasco

Based on neuront's response I created a simple JQuery method that gets the form data in key-value pairs but it works for multi-selects and for array inputs with name='example[]'.

This is how it is used:

var form_data = $("#form").getFormObject();

You can find an example below of its definition and how it works.

// Function start $.fn.getFormObject = function() { var object = $(this).serializeArray().reduce(function(obj, item) { var name = item.name.replace("[]", ""); if ( typeof obj[name] !== "undefined" ) { if ( !Array.isArray(obj[name]) ) { obj[name] = [ obj[name], item.value ]; } else { obj[name].push(item.value); } } else { obj[name] = item.value; } return obj; }, {}); return object; } // Function ends // This is how it's used $("#getObject").click( function() { var form_data = $("#form").getFormObject(); console.log(form_data); }); /* Only to make view better ;) */ #getObject { padding: 10px; cursor:pointer; background:#0098EE; color:white; display:inline-block; }

Get object (check the console!)


n
numediaweb

You can also use the FormData Objects; The FormData object lets you compile a set of key/value pairs to send using XMLHttpRequest. Its primarily intended for use in sending form data, but can be used independently from forms in order to transmit keyed data.

        var formElement = document.getElementById("myform_id");
        var formData = new FormData(formElement);
        console.log(formData);

g
gamliela

This will append all form fields to the JavaScript object "res":

var res = {};
$("#form input, #form select, #form textarea").each(function(i, obj) {
    res[obj.name] = $(obj).val();
})

G
George John
var formData = new FormData($('#form-id'));
params   = $('#form-id').serializeArray();

$.each(params, function(i, val) {
    formData.append(val.name, val.value);
});

S
Shlomi Hassid

For those of you who would prefer an Object as opposed to a serialized string (like the one returned by $(form).serialize(), and a slight improvement on $(form).serializeArray()), feel free to use the code below:

var Form = {
    _form: null,
    _validate: function(){
        if(!this._form || this._form.tagName.toLowerCase() !== "form") return false;
        if(!this._form.elements.length) return false;
        return true;
    }, _loopFields: function(callback){
        var elements = this._form.elements;
        for(var i = 0; i < elements.length; i++){
            var element = form.elements[i];
            if(name !== ""){
                callback(this._valueOfField(element));
            }
        }
    }, _valueOfField: function(element){
        var type = element.type;
        var name = element.name.trim();
        var nodeName = element.nodeName.toLowerCase();
        switch(nodeName){
            case "input":
                if(type === "radio" || type === "checkbox"){
                    if(element.checked){
                        return element.value;
                    }
                }
                return element.value;
                break;
            case "select":
                if(type === "select-multiple"){
                    for(var i = 0; i < element.options.length; i++){
                        if(options[i].selected){
                            return element.value;
                        }
                    }
                }
                return element.value;
                break;
            case "button":
                switch(type){
                    case "reset": 
                    case "submit": 
                    case "button":
                        return element.value;
                        break;
                }
                break;
        } 
    }, serialize: function(form){
        var data = {};
        this._form = form;

        if(this._validate()){
            this._loopFields(function(value){
                if(value !== null) data[name] = value;
            });
        }
        return data;
    }
};

To execute it, just use Form.serialize(form) and the function will return an Object similar to this:

<!-- { username: "username", password: "password" } !-->
<input type="text" value="username">
<input type="password" value="password">

As a bonus, it means you don't have to install the entire bundle of jQuery just for one serialize function.


In general I like implementing your own solution for serialization - especially if you want later to implement more custom functionality +1 - That said you have an error in the _validate method you need to return true....
C
Cezary Wojtkowski

I wrote a library to solve this very problem: JSONForms. It takes a form, goes through each input and builds a JSON object you can easily read.

Say you have the following form:

<form enctype='application/json'>
  <input name='places[0][city]' value='New York City'>
  <input type='number' name='places[0][population]' value='8175133'>
  <input name='places[1][city]' value='Los Angeles'>
  <input type='number' name='places[1][population]' value='3792621'>
  <input name='places[2][city]' value='Chicago'>
  <input type='number' name='places[2][population]' value='2695598'>
</form>

Passing the form to JSONForms' encode method returns you the following object:

{
  "places": [
    {
      "city": "New York City",
      "population": 8175133
    },
    {
      "city": "Los Angeles",
      "population": 3792621
    },
    {
      "city": "Chicago",
      "population": 2695598
    }
  ]
}

Here's demo with your form.


郭润民
function getFormData($form){
    var unindexed_array = $form.serializeArray();
    var indexed_array = {};

    $.map(unindexed_array, function(n, i){
        if(indexed_array[n['name']] == undefined){
            indexed_array[n['name']] = [n['value']];
        }else{
            indexed_array[n['name']].push(n['value']);
        }
    });

    return indexed_array;
}

M
Marcos Costa

you can use this function for have an object or a JSON from form.

for use it:

var object = formService.getObjectFormFields("#idform");

function getObjectFormFields(formSelector) { ///

Função que retorna objeto com base nas propriedades name dos elementos do formulário. /// Seletor do formulário var form = $(formSelector); var result = {}; var arrayAuxiliar = []; form.find(":input:text").each(function (index, element) { var name = $(element).attr('name'); var value = $(element).val(); result[name] = value; }); form.find(":input[type=hidden]").each(function (index, element) { var name = $(element).attr('name'); var value = $(element).val(); result[name] = value; }); form.find(":input:checked").each(function (index, element) { var name; var value; if ($(this).attr("type") == "radio") { name = $(element).attr('name'); value = $(element).val(); result[name] = value; } else if ($(this).attr("type") == "checkbox") { name = $(element).attr('name'); value = $(element).val(); if (result[name]) { if (Array.isArray(result[name])) { result[name].push(value); } else { var aux = result[name]; result[name] = []; result[name].push(aux); result[name].push(value); } } else { result[name] = []; result[name].push(value); } } }); form.find("select option:selected").each(function (index, element) { var name = $(element).parent().attr('name'); var value = $(element).val(); result[name] = value; }); arrayAuxiliar = []; form.find("checkbox:checked").each(function (index, element) { var name = $(element).attr('name'); var value = $(element).val(); result[name] = arrayAuxiliar.push(value); }); form.find("textarea").each(function (index, element) { var name = $(element).attr('name'); var value = $(element).val(); result[name] = value; }); return result; }


a
antelove

$( "form" ).bind( "submit", function(e) { e.preventDefault(); console.log( $(this).serializeObject() ); //console.log( $(this).serialize() ); //console.log( $(this).serializeArray() ); }); $.fn.serializeObject = function() { var o = {}; var a = this.serializeArray(); $.each( a, function() { if ( o[this.name] !== undefined) { if ( ! o[this.name].push ) { o[this.name] = [o[this.name]]; } o[this.name].push(this.value || ''); } else { o[this.name] = this.value || ''; } }); return o; };

Codepen


L
Long Tran

I'm kind of supprised because no one mentioned below solution.

Get form data via document.forms.namedItem function

var form = document.forms.namedItem("fileinfo");

form.addEventListener('submit', function(ev) {
   var oData = new FormData(form);
}

The HT

<form name="fileinfo">
  <label>Your email address:</label>
  <input type="email" autocomplete="on" autofocus name="userid" placeholder="email" required size="32" maxlength="64" /><br />
  <label>Custom file label:</label>
  <input type="text" name="filelabel" size="12" maxlength="32" /><br />
  <label>File to stash:</label>
  <input type="file" name="file" required />
  <input type="submit" value="Stash the file!" />
</form>
<div></div>

I
István

I wrote a function that takes care of multiple checkboxes and multiple selects. In those cases it returns an array.

function getFormData(formId) {
    return $('#' + formId).serializeArray().reduce(function (obj, item) {
        var name = item.name,
            value = item.value;

        if (obj.hasOwnProperty(name)) {
            if (typeof obj[name] == "string") {
                obj[name] = [obj[name]];
                obj[name].push(value);
            } else {
                obj[name].push(value);
            }
        } else {
            obj[name] = value;
        }
        return obj;
    }, {});
}

A
Amaan Iqbal

showing form input element fields and input file to submit your form without page refresh and grab all values with file include in it here it is

$('#imageUploadForm').on('submit',(function(e) { fname = $('#fname').val(); lname = $('#lname').val(); address = $('#address').val(); phoneno = $('#phoneno').val(); file = $('#file').val(); e.preventDefault(); var formData = new FormData(this); formData.append('file', $('#file')[0]); formData.append('fname',$('#fname').val()); formData.append('lname',$('#lname').val()); formData.append('phoneno',$('#phoneno').val()); formData.append('address',$('#address').val()); $.ajax({ type:'POST', url: "test.php", //url: '', data:formData, cache:false, contentType: false, processData: false, success:function(data) { alert('Data with file are submitted !'); } }); }))


A
Amaan Iqbal
$(form).serializeArray().reduce(function (obj, item) {
      if (obj[item.name]) {
           if ($.isArray(obj[item.name])) {
               obj[item.name].push(item.value);
           } else {
                var previousValue = obj[item.name];
                obj[item.name] = [previousValue, item.value];
           }
      } else {
           obj[item.name] = item.value;
      }

     return obj;
}, {});

It will fix issue:couldn't work with multiselects.


a
antman3351

Here's my version in vanilla JS (tested on Chrome)

works with:

name="input"

name="form[name]" (creates an object)

name="checkbox[]" (creates an object with an array)

name="form[checkbox][]" (creates an array)

name="form[select][name]" (creates an object with an object containing only the selected value)

/**
 * Get the values from a form
 * @param formId ( ID without the # )
 * @returns {object}
 */
function getFormValues( formId )
{
    let postData = {};
    let form = document.forms[formId];
    let formData = new FormData( form );

    for ( const value of formData.entries() )
    {
        let container = postData;
        let key = value[0];
        let arrayKeys = key.match( /\[[\w\-]*\]/g ); // Check for any arrays

        if ( arrayKeys !== null )
        {
            arrayKeys.unshift( key.substr( 0, key.search( /\[/ ) ) );  // prepend the first key to the list
            for ( let i = 0, count = arrayKeys.length, lastRun = count - 1; i < count; i++ )
            {
                let _key = arrayKeys[i];
                _key = _key.replace( "[", '' ).replace( "]", '' ); // Remove the brackets []
                if ( _key === '' )
                {
                    if ( ! Array.isArray( container ) )
                    {
                        container = [];
                    }

                    _key = container.length;
                }

                if ( ! (_key in container) ) // Create an object for the key if it doesn't exist
                {
                    if ( i !== lastRun && arrayKeys[i + 1] === '[]' )
                    {
                        container[_key] = [];
                    }
                    else
                    {
                        container[_key] = {};
                    }
                }

                if ( i !== lastRun ) // Until we're the last item, swap container with it's child
                {
                    container = container[_key];
                }

                key = _key;
            }
        }
        container[key] = value[1]; // finally assign the value
    }

    return postData;
}

A
Alexander

You are all not fully correct. You cannot write:

formObj[input.name] = input.value;

Because this way if you have multiselect list - its values will be overwritten with the last one, since it's transmitted as: "param1" : "value1", "param1" : "value2".

So, correct approach is:

if (formData[input.name] === undefined) {
    formData[input.name] = input.value;
}
else {
    var inputFieldArray = $.merge([], $.isArray(formData[input.name]) ? formData[input.name] : [formData[input.name]]);
    $.merge(inputFieldArray, [input.value]);
    formData[input.name] = $.merge([], inputFieldArray);
}

u
user1101791

This method should do it. It serializes the form data and then converts them to an object. Takes care of groups of checkboxes as well.

function getFormObj(formId) {
  var formParams = {};
  $('#' + formId)
    .serializeArray()
    .forEach(function(item) {
      if (formParams[item.name]) {
        formParams[item.name] = [formParams[item.name]];
        formParams[item.name].push(item.value)
      } else {
        formParams[item.name] = item.value
      }
    });
  return formParams;
}