• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
JavaScriptSource

JavaScriptSource

Search 5,000+ Free JavaScript Snippets

  • Home
  • Browse Snippets
    • Addon
    • Ajax
    • Buttons
    • Cookies
    • CSS
    • Featured
    • Forms
    • Games
    • Generators
    • Image Effects
    • Math Related
    • Miscellaneous
    • Multimedia
    • Navigation
    • Page Details
    • Passwords
    • Text Effects
    • Time & Date
    • User Details
Home / Forms / Serialize form data into a query string

Serialize form data into a query string

Serialize form data into a query string

The following function serializes the form data which consists of names and values of its fields:

const serialize = function(formEle) {
    // Get all fields
    const fields = [].slice.call(formEle.elements, 0);

    return fields
        .map(function(ele) {
            const name = ele.name;
            const type = ele.type;
            
            // We ignore
            // - field that doesn't have a name
            // - disabled field
            // - `file` input
            // - unselected checkbox/radio
            if (!name ||
                ele.disabled ||
                type === 'file' ||
                (/(checkbox|radio)/.test(type) && !ele.checked))
            {
                return '';
            }

            // Multiple select
            if (type === 'select-multiple') {
                return ele.options
                    .map(function(opt) {
                        return opt.selected
                            ? `${encodeURIComponent(name)}=${encodeURIComponent(opt.value)}`
                            : '';
                    })
                    .filter(function(item) {
                        return item;
                    })
                    .join('&');
            }

            return `${encodeURIComponent(name)}=${encodeURIComponent(ele.value)}`;
        })
        .filter(function(item) {
            return item;
        })
        .join('&');
};

Note that we convert the collection of form elements to array by

const fields = [].slice.call(formEle.elements, 0)

Source

https://htmldom.dev/serialize-form-data-into-a-query-string/

Forms

Related Snippets:

  • Create a range slider
  • Country State City Drop Down List
  • Validate Numeric Only
  • Input Mask

Primary Sidebar

Popular Posts

Story Generator

IP Grabber – get a users IP address with JavaScript

Simple Calendar

Remove Ads

Astrological Calculator

Copyright © 2025 JavaScriptSource.com

  • About
  • Privacy Policy
  • FAQ
  • Jobs For Developers