[javascript] 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;
});

This question is related to javascript jquery forms

The answer is


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;

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"
}

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.


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;
}

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

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

_x000D_
_x000D_
$( "form" ).bind( "submit", function(e) {_x000D_
    e.preventDefault();_x000D_
    _x000D_
    console.log(  $(this).serializeObject() );    _x000D_
_x000D_
    //console.log(  $(this).serialize() );_x000D_
    //console.log(  $(this).serializeArray() );_x000D_
_x000D_
});_x000D_
_x000D_
_x000D_
$.fn.serializeObject = function() {_x000D_
    var o = {};_x000D_
    var a = this.serializeArray();_x000D_
_x000D_
    $.each( a, function() {_x000D_
        if ( o[this.name] !== undefined) _x000D_
        {_x000D_
            if ( ! o[this.name].push ) _x000D_
            {_x000D_
                o[this.name] = [o[this.name]];_x000D_
            }_x000D_
            o[this.name].push(this.value || '');_x000D_
        }_x000D_
        else _x000D_
        {_x000D_
            o[this.name] = this.value || '';_x000D_
        }_x000D_
    });_x000D_
_x000D_
    return o;_x000D_
};
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>_x000D_
_x000D_
<form>_x000D_
_x000D_
    <input type="radio" name="foo" value="1" checked="checked" />_x000D_
    <input type="radio" name="foo" value="0" />_x000D_
    <input name="bar" value="xxx" />_x000D_
_x000D_
    <select name="this">_x000D_
        <option value="hi" selected="selected">Hi</option>_x000D_
        <option value="ho">Ho</option>_x000D_
    </select>_x000D_
_x000D_
    <input type="submit" value="Submit" />_x000D_
_x000D_
</form>
_x000D_
_x000D_
_x000D_

Codepen


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


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();
})

$("#form input, #form select, #form textarea").each(function() {
 data[theFieldName] = theFieldValue;
});

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


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;
}

Here is a nice vanilla JS function I wrote to extract form data as an object. It also has options for inserting additions into the object, and for clearing the form input fields.

const extractFormData = ({ form, clear, add }) => {
  return [].slice.call(form.children).filter(node => node.nodeName === 'INPUT')
  .reduce((formData, input) => {
    const value = input.value
    if (clear) { input.value = '' }
    return {
      ...formData,
      [input.name]: value
    }
  }, add)
}

Here is an example of its use with a post request:

submitGrudge(e) {
  e.preventDefault()

  const form = e.target
  const add = { id: Date.now(), forgiven: false }
  const grudge = extractFormData({ form, add, clear: true })

  // grudge = {
  //  "name": "Example name",
  //  "offense": "Example string",
  //  "date": "2017-02-16",
  //  "id": 1487877281983,
  //  "forgiven": false
  // }

  fetch('http://localhost:3001/api/grudge', {
    method: 'post',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(grudge)
  })
    .then(response => response.json())
    .then(grudges => this.setState({ grudges }))
    .catch(err => console.log('error: ', err))
}

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;
}

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.


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

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

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);
}

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.


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.


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

for use it:

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

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


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:

_x000D_
_x000D_
    function setOrPush(target, val) {_x000D_
      var result = val;_x000D_
      if (target) {_x000D_
        result = [target];_x000D_
        result.push(val);_x000D_
      }_x000D_
      return result;_x000D_
    }_x000D_
_x000D_
    function getFormResults(formElement) {_x000D_
      var formElements = formElement.elements;_x000D_
      var formParams = {};_x000D_
      var i = 0;_x000D_
      var elem = null;_x000D_
      for (i = 0; i < formElements.length; i += 1) {_x000D_
        elem = formElements[i];_x000D_
        switch (elem.type) {_x000D_
          case 'submit':_x000D_
            break;_x000D_
          case 'radio':_x000D_
            if (elem.checked) {_x000D_
              formParams[elem.name] = elem.value;_x000D_
            }_x000D_
            break;_x000D_
          case 'checkbox':_x000D_
            if (elem.checked) {_x000D_
              formParams[elem.name] = setOrPush(formParams[elem.name], elem.value);_x000D_
            }_x000D_
            break;_x000D_
          default:_x000D_
            formParams[elem.name] = setOrPush(formParams[elem.name], elem.value);_x000D_
        }_x000D_
      }_x000D_
      return formParams;_x000D_
    }_x000D_
_x000D_
    //_x000D_
    // Boilerplate for running the snippet/form_x000D_
    //_x000D_
_x000D_
    function ok() {_x000D_
      var params = getFormResults(document.getElementById('main_form'));_x000D_
      document.getElementById('results_wrapper').innerHTML = JSON.stringify(params, null, ' ');_x000D_
    }_x000D_
_x000D_
    (function() {_x000D_
      var main_form = document.getElementById('main_form');_x000D_
      main_form.addEventListener('submit', function(event) {_x000D_
        event.preventDefault();_x000D_
        ok();_x000D_
      }, false);_x000D_
    })();
_x000D_
<form id="main_form">_x000D_
  <div id="questions_wrapper">_x000D_
    <p>what is a?</p>_x000D_
    <div>_x000D_
      <input type="radio" required="" name="q_0" value="a" id="a_0">_x000D_
      <label for="a_0">a</label>_x000D_
      <input type="radio" required="" name="q_0" value="b" id="a_1">_x000D_
      <label for="a_1">b</label>_x000D_
      <input type="radio" required="" name="q_0" value="c" id="a_2">_x000D_
      <label for="a_2">c</label>_x000D_
      <input type="radio" required="" name="q_0" value="d" id="a_3">_x000D_
      <label for="a_3">d</label>_x000D_
    </div>_x000D_
    <div class="question range">_x000D_
      <label for="a_13">A?</label>_x000D_
      <input type="range" required="" name="q_3" id="a_13" min="0" max="10" step="1" list="q_3_dl">_x000D_
      <datalist id="q_3_dl">_x000D_
        <option value="0"></option>_x000D_
        <option value="1"></option>_x000D_
        <option value="2"></option>_x000D_
        <option value="3"></option>_x000D_
        <option value="4"></option>_x000D_
        <option value="5"></option>_x000D_
        <option value="6"></option>_x000D_
        <option value="7"></option>_x000D_
        <option value="8"></option>_x000D_
        <option value="9"></option>_x000D_
        <option value="10"></option>_x000D_
      </datalist>_x000D_
    </div>_x000D_
    <p>A and/or B?</p>_x000D_
    <div>_x000D_
      <input type="checkbox" name="q_4" value="A" id="a_14">_x000D_
      <label for="a_14">A</label>_x000D_
      <input type="checkbox" name="q_4" value="B" id="a_15">_x000D_
      <label for="a_15">B</label>_x000D_
    </div>_x000D_
  </div>_x000D_
  <button id="btn" type="submit">OK</button>_x000D_
</form>_x000D_
<div id="results_wrapper"></div>
_x000D_
_x000D_
_x000D_

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.


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;
    }, {});
}

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.

_x000D_
_x000D_
// Function start_x000D_
$.fn.getFormObject = function() {_x000D_
    var object = $(this).serializeArray().reduce(function(obj, item) {_x000D_
        var name = item.name.replace("[]", "");_x000D_
        if ( typeof obj[name] !== "undefined" ) {_x000D_
            if ( !Array.isArray(obj[name]) ) {_x000D_
                obj[name] = [ obj[name], item.value ];_x000D_
            } else {_x000D_
               obj[name].push(item.value);_x000D_
            }_x000D_
        } else {_x000D_
            obj[name] = item.value;_x000D_
        }_x000D_
        return obj;_x000D_
    }, {});_x000D_
    return object;_x000D_
}_x000D_
// Function ends_x000D_
_x000D_
// This is how it's used_x000D_
$("#getObject").click( function() {_x000D_
  var form_data = $("#form").getFormObject();_x000D_
  console.log(form_data);_x000D_
});
_x000D_
/* Only to make view better ;) */_x000D_
#getObject {_x000D_
  padding: 10px;_x000D_
  cursor:pointer;_x000D_
  background:#0098EE;_x000D_
  color:white;_x000D_
  display:inline-block;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>_x000D_
<form id="form">_x000D_
  <input type="text" name="text" value="Hola amigo" /> _x000D_
  _x000D_
  <input type="text" name="text_array[]" value="Array 1" /> _x000D_
  <input type="text" name="text_array[]" value="Array 2" /> _x000D_
  <input type="text" name="text_array[]" value="Array 3" /> _x000D_
  _x000D_
  <select name="multiselect" multiple>_x000D_
    <option name="option1" selected> option 1 </option>_x000D_
    <option name="option2" selected> option 2 </option>_x000D_
  </select>_x000D_
  _x000D_
  <input type="checkbox" name="checkbox" value="checkbox1" checked/>_x000D_
  <input type="checkbox" name="checkbox" value="checkbox2" checked/>_x000D_
  _x000D_
  <input type="radio" name="radio" value="radio1" checked/>_x000D_
  <input type="radio" name="radio" value="radio2"/>_x000D_
_x000D_
</form>_x000D_
_x000D_
<div id="getObject"> Get object (check the console!) </div>
_x000D_
_x000D_
_x000D_


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

_x000D_
_x000D_
<form id="imageUploadForm"   action="" method="post" enctype="multipart/form-data">_x000D_
<input type="text" class="form-control" id="fname" name='fname' placeholder="First Name" >_x000D_
<input type="text" class="form-control" name='lname' id="lname" placeholder="Last Name">_x000D_
<input type="number" name='phoneno'  class="form-control" id="phoneno" placeholder="Phone Number">_x000D_
<textarea class="form-control" name='address' id="address" rows="5" cols="5" placeholder="Your Address"></textarea>_x000D_
<input type="file" name="file" id="file" >_x000D_
<input type="submit" id="sub" value="Registration">        _x000D_
</form>
_x000D_
_x000D_
_x000D_ on Submit button page will send ajax request to your php file.
_x000D_
_x000D_
$('#imageUploadForm').on('submit',(function(e) _x000D_
{_x000D_
     fname = $('#fname').val();_x000D_
     lname =  $('#lname').val();_x000D_
     address =  $('#address').val();_x000D_
     phoneno =  $('#phoneno').val();_x000D_
     file =  $('#file').val();_x000D_
     e.preventDefault();_x000D_
     var formData = new FormData(this);_x000D_
     formData.append('file', $('#file')[0]);_x000D_
     formData.append('fname',$('#fname').val());_x000D_
     formData.append('lname',$('#lname').val());_x000D_
     formData.append('phoneno',$('#phoneno').val());_x000D_
     formData.append('address',$('#address').val());_x000D_
     $.ajax({_x000D_
  type:'POST',_x000D_
                url: "test.php",_x000D_
                //url: '<?php echo base_url().'edit_profile/edit_profile2';?>',_x000D_
_x000D_
                data:formData,_x000D_
                cache:false,_x000D_
                contentType: false,_x000D_
                processData: false,_x000D_
                success:function(data)_x000D_
                {_x000D_
                     alert('Data with file are submitted !');_x000D_
_x000D_
                }_x000D_
_x000D_
     });_x000D_
_x000D_
}))
_x000D_
_x000D_
_x000D_


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;
}

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


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();

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);

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;
}

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;
    }, _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.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to forms

How do I hide the PHP explode delimiter from submitted form results? React - clearing an input value after form submit How to prevent page from reloading after form submit - JQuery Input type number "only numeric value" validation Redirecting to a page after submitting form in HTML Clearing input in vuejs form Cleanest way to reset forms Reactjs - Form input validation No value accessor for form control TypeScript-'s Angular Framework Error - "There is no directive with exportAs set to ngForm"