form serialize javascript (no framework)

后端 未结 23 1631
一生所求
一生所求 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 16:46

    Using JavaScript reduce function should do a trick for all browsers, including IE9 >:

    Array.prototype.slice.call(form.elements) // convert form elements to array
        .reduce(function(acc,cur){   // reduce 
            var o = {type : cur.type, name : cur.name, value : cur.value}; // get needed keys
            if(['checkbox','radio'].indexOf(cur.type) !==-1){
                o.checked = cur.checked;
            } else if(cur.type === 'select-multiple'){
                o.value=[];
                for(i=0;i

    Live example bellow.

    var _formId = document.getElementById('formId'),
        formData = Array.prototype.slice.call(_formId.elements).reduce(function(acc,cur,indx,arr){
            var i,o = {type : cur.type, name : cur.name, value : cur.value};
            if(['checkbox','radio'].indexOf(cur.type) !==-1){
                o.checked = cur.checked;
            } else if(cur.type === 'select-multiple'){
                o.value=[];
                for(i=0;i
    Checkbox 1 Checkbox 2 Radio Btn 1 Radio Btn 2

提交回复
热议问题