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

- 1,151
- 9
- 11
-
2Note that formData.get() doesn't have full browser support: https://caniuse.com/mdn-api_formdata_get – HaroldtheSquare Jun 23 '21 at 20:30
-
16As at this writing, it has a support of 94.55% from https::caniuse.com/mdn-api_formdata_get. So I think thats fine. By the way, who still develops for Internet Explorer? – Olu Adeyemo Jan 02 '22 at 01:59
-
You can get all fields using `Object.fromEntries(formData);` – Lekia Jul 08 '23 at 15:07
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.

- 13,361
- 4
- 40
- 45
-
-
1
-
3Warning: `e.value` always returns `on` for checkboxes! Workaround: Insert `var value = e.getAttribute("type") == "checkbox" ? e.checked : e.value` and use `value` instead of `e.value`. – Martin M. Jun 05 '17 at 22:18
-
3NOTICE: "e.value always returns on for checkboxes!" No it doesn't! Just set the value attribute for the checkbox, either directly in the html, or via js. Ex: – Self Evident Mar 31 '18 at 16:42
-
[Accessing form controls](https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/elements#accessing_form_controls) – Eugen Konkov Sep 11 '21 at 13:50
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();

- 7,868
- 11
- 48
- 86

- 24,974
- 34
- 121
- 164
-
2The problem with this, is that when using checkboxes, the data doesn't show up at all, I would rather it just be set to false. – Dustin Poissant Nov 20 '16 at 19:52
-
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 + "]");
});

- 11,300
- 15
- 49
- 66
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, ...
-
Does this work correctly for checkboxes, radio buttons and multi-selects? – SpoonMeiser Oct 20 '09 at 08:48
-
AFAIK - yes, because checkbox and radio button have 'name' and 'value' attributes/properties. The only one I'm not really sure is Listbox, because it has a child collection with Option elements. – markom Oct 21 '09 at 08:35
-
2first line must be var params =''; to avoid 'undefined' in the final string – Slemgrim Oct 30 '12 at 12:39
-
2@SpoonMeiser @muerte No. This grabs the `value` attribute of each element, regardless of the state of the `checked` attribute. You'll get checkboxname=valueattribute for each checkbox, and radioname=valueattribute for each radio. The latter is even more broken if you put them into an array, as each radio element will overwrite the previous, and you're left with array['radioname']=lastvalueattribute. – Erics Jan 15 '17 at 23:13
-
Danger. That code is too simple. You aren't escaping special characters in the data so if a field contained (for example) `&` then it would break. – Quentin Sep 24 '22 at 07:58
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()
.

- 18,421
- 1
- 62
- 57
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();

- 5,079
- 2
- 28
- 29
You can get the form using a document.getElementById and returning the elements[] array.
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.

- 1,590
- 1
- 12
- 15
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 );
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

- 3,585
- 5
- 31
- 41