It took me two consecutive nights of searching, but I finally decided on what I consider is the best form data to query string function. Factors that contributed to this decision:
- It is a self-contained function
- It isn’t incredibly long
- It works for most form inputs
The exceptions are reset, button, image, and file input types, which are simply ignored by the function.
I did have to make one modification to the original code so that the checkbox values would output as an array, rather than as a comma-delimited list, which was inconsistent with the way checkbox arrays are normally handled.
The Function
function formDataToQueryString(docForm) {
var submitContent = '';
var formElem;
var lastElemName = '';
for(i = 0; i < docForm.elements.length; i++ ) {
formElem = docForm.elements[i];
switch( formElem.type ) {
// Text fields, hidden form elements
case 'text':
case 'hidden':
case 'password':
case 'textarea':
case 'select-one':
submitContent += formElem.name + '=' + escape(formElem.value) + '&';
break;
// Radio buttons
case 'radio':
if( formElem.checked ) submitContent += formElem.name + '=' + escape(formElem.value) + '&';
break;
// Checkboxes
case 'checkbox':
if( formElem.checked ) {
// Continuing multiple, same-name checkboxes
if( formElem.name == lastElemName ) {
// Strip off end ampersand if there is one
if( submitContent.lastIndexOf('&') == submitContent.length-1 ) {
submitContent = submitContent.substr(0, submitContent.length - 1);
}
submitContent += '&' + formElem.name + '=' + escape(formElem.value);
} else {
submitContent += formElem.name + '=' + escape(formElem.value);
}
submitContent += '&';
lastElemName = formElem.name;
}
break;
}
}
// Remove trailing separator
submitContent = submitContent.substr(0, submitContent.length - 1);
return submitContent;
}
Example
If you have a form with id of myForm, you could display the result of the function with the following code:
var queryString = formDataToQueryString( document.getElementById('myForm') );
alert(queryString);
This function is especially useful in AJAX applications, where form data is oftentimes posted via XMLHttpRequest in query string format.
If you change the first section where all the cases overlap to check for the in the value and then do a encodeURIComponent you will be able to have people use the & in the text that they use. For example:
if (formElem.value.search(“&”) > -1) {
submitContent += formElem.name + ‘=’ + encodeURIComponent(formElem.value) + ‘&’;
}