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.
views:
935answers:
6You 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.
You can use this simple loop to get all the element names and their values.
var params;
for(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, ...
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
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();
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.
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 + "]");
});