The formDataToQueryString Function

A note from A Beautiful Site’s founder: We developed Surreal to be easy for you and your clients. If you’re a web designer, you should take a look at the simple, hosted CMS that’s changing the way content is managed. Surreal integrates in moments and is trusted by over 18,000 websites. Try it out for free and let us know what you think! Visit Website »

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 enjoyed this article, please share it with a friend!

One Response to The formDataToQueryString Function

  1. Robert says:

    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) + ‘&’;
    }

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>