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

Question!

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.



Answers

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


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.prototype.toString.call(arg)==='[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 = field.name || field.id;
    if (field.type==='button' || field.type==='image' || field.type==='submit' || !sKey) continue;
    switch (field.type) {
      case 'checkbox':
        o[sKey] = +field.checked;
        break;
      case 'radio':
        if (o[sKey]===undefined) o[sKey] = '';
        if (field.checked) o[sKey] = field.value;
        break;
      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;
        break;
      default:
        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];
        break;
      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;
          }
        }
        break;
      default:
        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">
  <table>
    <tr>
      <td><label for="username">Username:</label></td>
      <td><input type="text" id="username" name="username" value="Tom"></td>
    </tr>
    <tr>
      <td><label for="phone">Phone:</label></td>
      <td><input type="number" id="phone" name="phone" value="7672676"></td>
    </tr>
    <tr>
      <td><label for="avatar">Avatar:</label></td>
      <td><input type="file" id="avatar" name="avatar"></td>
    </tr>
    <tr>
      <td><label>Gender:</label></td>
      <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>
    </tr>
    <tr>
      <td><label for="private">Private:</label></td>
      <td><input type="checkbox" id="private" name="private"></td>
    </tr>
    <tr>
      <td><label for="friends">Friends:</label></td>
      <td>
        <select id="friends" name="friends" size="2" multiple>
          <option>Dick</option>
          <option>Harry</option>
        </select>
      </td>
    </tr>
    <tr>
      <td><label for="theme">Theme:</label></td>
      <td>
        <select id="theme" name="theme">
          <option value="">-- Select --</option>
          <option value="dark">Dark</option>
          <option value="light">Light</option>
        </select>
      </td>
    </tr>
    <tr>
      <td><label for="bio">Bio:</label></td>
      <td><textarea id="bio" name="bio"></textarea></td>
    </tr>
    <tr>
      <td colspan="2">
        <input type="submit" value="Submit">
        <button>Cancel</button>
      </td>
    </tr>
  </table>
</form>
<p>
  <button onclick="formDataToObject(document.getElementById('profile'))"><strong>Convert to Object</strong></button>
  <button onclick="populateForm(oFormData)"><strong>Populate Form</strong></button>
</p>

You can also play around with it in this pen: http://codepen.io/thdoan/pen/EyawvR

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

By : 10basetom


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, ...
By : muerte


This video can help you solving your question :)
By: admin