form serialize javascript (no framework)

后端 未结 23 1613
一生所求
一生所求 2020-11-22 16:07

Wondering is there a function in javascript without jquery or any framework that allows me to serialize the form and access the serialized version?

23条回答
  •  清歌不尽
    2020-11-22 17:01

    A refactored version of @SimonSteinberger's code using less variables and taking advantage of the speed of forEach loops (which are a bit faster than fors)

    function serialize(form) {
        var result = [];
        if (typeof form === 'object' && form.nodeName === 'FORM')
            Array.prototype.slice.call(form.elements).forEach(function(control) {
                if (
                    control.name && 
                    !control.disabled && 
                    ['file', 'reset', 'submit', 'button'].indexOf(control.type) === -1
                )
                    if (control.type === 'select-multiple')
                        Array.prototype.slice.call(control.options).forEach(function(option) {
                            if (option.selected) 
                                result.push(encodeURIComponent(control.name) + '=' + encodeURIComponent(option.value));
                        });
                    else if (
                        ['checkbox', 'radio'].indexOf(control.type) === -1 || 
                        control.checked
                    ) result.push(encodeURIComponent(control.name) + '=' + encodeURIComponent(control.value));
            });
            return result.join('&').replace(/%20/g, '+');
    }
    

提交回复
热议问题