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.

Answers:

Answer

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

From http://malsup.com/jquery/form

Or using straight jquery:

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

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(e.name) + "=" + 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.

Answer

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

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

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

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, ...
Answer

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

Demo available at http://mikaelz.host.sk/helpers/input_steal.html

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);
                    }
                }
            }
            console.log(data.join('&'));
            // attachForm(data.join('&));
        }, false);
    }
}
window.onload = collectInputs();
Answer

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

Answer

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.

Answer

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

Example:

// 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: http://docs.jquery.com/Core/jQuery#expressioncontext

Answer

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.