How can I get all a form's values that would be submitted without submitting [duplicate]

I have a form on my page and am dynamically adding controls to the form with Javascript/JQuery. At some point I need to get all the values in the form on the client side as a collection or a query string. I don't want to submit the form because I want to pass the form values along with other information that I have on the client to a back-end WCF/Ajax service method. So I'm trying to figure out how to capture all the values in the same type of collection that the form would normally send to the server if the form was actually submitted. I suspect there is an easy way to capture this, but I'm stumped.



The jquery form plugin offers an easy way to iterate over your form elements and put them in a query string. It might also be useful for whatever else you need to do with these values.

var queryString = $('#myFormId').formSerialize();


Or using straight jquery:

var queryString = $('#myFormId').serialize();

In straight Javascript you could do something similar to the following:

var kvpairs = [];
var form = // get the form somehow
for ( var i = 0; i < form.elements.length; i++ ) {
   var e = form.elements[i];
   kvpairs.push(encodeURIComponent( + "=" + encodeURIComponent(e.value));
var queryString = kvpairs.join("&");

In short, this creates a list of key-value pairs (name=value) which is then joined together using "&" as a delimiter.


If your form tag is like

<form action="" method="post" id="BookPackageForm">

Then fetch the form element by using forms object.

var formEl = document.forms.BookPackageForm;

Get the data from the form by using FormData objects.

var formData = new FormData(formEl);

Get the value of the fields by the form data object.

var name = formData.get('name');

Thanks Chris. That's what I was looking for. However, note that the method is serialize(). And there is another method serializeArray() that looks very useful that I may use. Thanks for pointing me in the right direction.

var queryString = $('#frmAdvancedSearch').serialize();

var fieldValuePairs = $('#frmAdvancedSearch').serializeArray();
$.each(fieldValuePairs, function(index, fieldValuePair) {
    alert("Item " + index + " is [" + + "," + fieldValuePair.value + "]");

You can use this simple loop to get all the element names and their values.

var params = '';
for( var i=0; i<document.FormName.elements.length; i++ )
   var fieldName = document.FormName.elements[i].name;
   var fieldValue = document.FormName.elements[i].value;

   // use the fields, put them in a array, etc.

   // or, add them to a key-value pair strings, 
   // as in regular POST

   params += fieldName + '=' + fieldValue + '&';

// send the 'params' variable to web service, GET request, ...

Thank you for your ideas. I created the following for my use

Demo available at

function collectInputs() {
    var forms = parent.document.getElementsByTagName("form");
    for (var i = 0;i < forms.length;i++) {
        forms[i].addEventListener('submit', function() {
            var data = [],
                subforms = parent.document.getElementsByTagName("form");

            for (x = 0 ; x < subforms.length; x++) {
                var elements = subforms[x].elements;
                for (e = 0; e < elements.length; e++) {
                    if (elements[e].name.length) {
                        data.push(elements[e].name + "=" + elements[e].value);
            // attachForm(data.join('&));
        }, false);
window.onload = collectInputs();

For those who don't use jQuery, below is my vanilla JavaScript function to create a form data object that can be accessed like any common object, unlike new FormData(form).

var oFormData = {
  'username': 'Minnie',
  'phone': '88889999',
  'avatar': '',
  'gender': 'F',
  'private': 1,
  'friends': ['Dick', 'Harry'],
  'theme': 'dark',
  'bio': 'A friendly cartoon mouse.'

function isObject(arg) {
  return'[object Object]';

function formDataToObject(elForm) {
  if (!elForm instanceof Element) return;
  var fields = elForm.querySelectorAll('input, select, textarea'),
    o = {};
  for (var i=0, imax=fields.length; i<imax; ++i) {
    var field = fields[i],
      sKey = ||;
    if (field.type==='button' || field.type==='image' || field.type==='submit' || !sKey) continue;
    switch (field.type) {
      case 'checkbox':
        o[sKey] = +field.checked;
      case 'radio':
        if (o[sKey]===undefined) o[sKey] = '';
        if (field.checked) o[sKey] = field.value;
      case 'select-multiple':
        var a = [];
        for (var j=0, jmax=field.options.length; j<jmax; ++j) {
          if (field.options[j].selected) a.push(field.options[j].value);
        o[sKey] = a;
        o[sKey] = field.value;
  alert('Form data:\n\n' + JSON.stringify(o, null, 2));
  return o;

function populateForm(o) {
  if (!isObject(o)) return;
  for (var i in o) {
    var el = document.getElementById(i) || document.querySelector('[name=' + i + ']');
    if (el.type==='radio') el = document.querySelectorAll('[name=' + i + ']');
    switch (typeof o[i]) {
      case 'number':
        el.checked = o[i];
      case 'object':
        if (el.options && o[i] instanceof Array) {
          for (var j=0, jmax=el.options.length; j<jmax; ++j) {
            if (o[i].indexOf(el.options[j].value)>-1) el.options[j].selected = true;
        if (el instanceof NodeList) {
          for (var j=0, jmax=el.length; j<jmax; ++j) {
            if (el[j].value===o[i]) el[j].checked = true;
        } else {
          el.value = o[i];
form {
  border: 1px solid #000;

tr {
  vertical-align: top;
<form id="profile" action="formdata.html" method="get">
      <td><label for="username">Username:</label></td>
      <td><input type="text" id="username" name="username" value="Tom"></td>
      <td><label for="phone">Phone:</label></td>
      <td><input type="number" id="phone" name="phone" value="7672676"></td>
      <td><label for="avatar">Avatar:</label></td>
      <td><input type="file" id="avatar" name="avatar"></td>
        <input type="radio" id="gender-m" name="gender" value="M"> <label for="gender-m">Male</label><br>
        <input type="radio" id="gender-f" name="gender" value="F"> <label for="gender-f">Female</label>
      <td><label for="private">Private:</label></td>
      <td><input type="checkbox" id="private" name="private"></td>
      <td><label for="friends">Friends:</label></td>
        <select id="friends" name="friends" size="2" multiple>
      <td><label for="theme">Theme:</label></td>
        <select id="theme" name="theme">
          <option value="">-- Select --</option>
          <option value="dark">Dark</option>
          <option value="light">Light</option>
      <td><label for="bio">Bio:</label></td>
      <td><textarea id="bio" name="bio"></textarea></td>
      <td colspan="2">
        <input type="submit" value="Submit">
  <button onclick="formDataToObject(document.getElementById('profile'))"><strong>Convert to Object</strong></button>
  <button onclick="populateForm(oFormData)"><strong>Populate Form</strong></button>

You can also play around with it in this pen:

UPDATE: I also added a function to populate the form with the object returned by formDataToObject().


You can get the form using a document.getElementById and returning the elements[] array.

Here is an example.

You can also get each field of the form and get its value using the document.getElementById function and passing in the field's id.


Depending on the type of input types you're using on your form, you should be able to grab them using standard jQuery expressions.


// change forms[0] to the form you're trying to collect elements from...  or remove it, if you need all of them
var input_elements = $("input, textarea", document.forms[0]);

Check out the documentation for jQuery expressions on their site for more info:


I think the following code will take care of only TextFields in the form:

var str = $('#formId').serialize();

To add other types of input type we can use:

$("input[type='checkbox'], input[type='radio']").on( "click", functionToSerialize );
$("select").on( "change", functionToSerialize );


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.