js: 將 form表單序列化

來源:互聯網
上載者:User

標籤:序列化   form   

form的序列化,即將表單中的索引值序列化為可提交的字串

 

表單

   <form id="target">       <select name="age">            <option value="age1">20</option>            <option value="age2" selected>21</option>        </select>        <input name="name" value="Cynthia">        <label>passsword</label>        <input type="password" name="password" value="123456">        <input type="hidden" name="salery" value="3333">        <textarea name="description" cols="15" rows="5">description</textarea>        <input type="checkbox" name="hobby" value="football" checked> Football        <input type="checkbox" name="hobby" value="basketball"> Basketball        <input type="radio" name="sex" value="Female" checked> Female        <input type="radio" name="sex" value="Male"> Male    </form>

方法一

        function serializeForm1(form){             var setForm = "";             for(var key in form){                 if(form.hasOwnProperty(key)){                     setForm += ‘"‘+form[key].name+‘"‘+‘:‘+‘"‘+form[key].value + ‘"‘+‘,‘;                }            }            setForm = "{" + setForm.slice(0,setForm.length -1) + "}";            console.log(setForm);            // console.log(JSON.parse(setForm));            return JSON.parse(setForm);        }                // 調用        var oForm = document.getElementById(‘target‘);        console.log(serializeForm3(oForm));

結果:

   650) this.width=650;" src="https://s1.51cto.com/wyfs02/M00/9E/3A/wKioL1mNpeHim-LyAABUQYSw4_I664.png" title="圖片3.png" alt="wKioL1mNpeHim-LyAABUQYSw4_I664.png" />


方法二

          function serializeForm2(form) {            var parts = [];            for (var i = 0, i1 = form.elements.length; i < i1; i++) {                var field = form.elements[i];                switch (field.type) {                    case ‘select-one‘:                    case ‘select-multiple‘:                        if (field.type.length) {                            for (var j = 0, j1 = field.options.length; j < j1; j++) {                                var option = field.options[j];                                if (option.selected) {                                    var optionValue = ‘‘;                                    if (option.hasAttribute(‘value‘) && option.attributes[‘value‘].specified) {                                        //specified表明是否有此屬性,有的話返回true,若定義了此屬性但尚未添加到元素中也返回true。                                        optionValue = option.value;                                    } else {                                        optionValue = optionValue.text;                                    }                                    parts.push(encodeURIComponent(field.name) + ‘=‘ + encodeURIComponent(optionValue));                                }                            }                        }                        break;                    case undefined:                    case ‘file‘:                    case ‘submit‘:                    case ‘reset‘:                    case ‘button‘:                        break;                    case ‘radio‘:                    case ‘checkbox‘:                        if(!field.checked){                            break;                        }else{                            parts.push(encodeURIComponent(field.name) + ‘=‘ + encodeURIComponent(field.dataset[‘index‘]));                            break;                        }                    default:                        if(field.name.length){                            parts.push(encodeURIComponent(field.name) + ‘=‘ + encodeURIComponent(field.value));                        }                }            }            return parts.join(‘&‘);        }                // 調用        var oForm = document.getElementById(‘target‘);                console.log(serializeForm2(oForm));

結果:

650) this.width=650;" src="https://s3.51cto.com/wyfs02/M02/9E/3A/wKioL1mNpcziTu1XAAAaj9QEcg0249.png" title="圖片2.png" alt="wKioL1mNpcziTu1XAAAaj9QEcg0249.png" />


方法三

        function serializeForm3(form){            if(!form||form.tagName.toUpperCase()!=‘FORM‘){                return false;            }            var res=[];            var tag,tagType,tagVal,tagName;            for(var i=0;i<form.length;i++){                tag=form[i];                tagType=form[i].type;                tagVal=form[i].value;                tagName=form[i].name;                  var reg1=/[‘textarea‘|‘text‘|‘passsword‘|‘label‘]/g;                var reg2=/[‘radio‘|‘checkbox‘]/g;                var reg3=/[‘select‘]/g;                if(reg1.test(tagType)){                    res.push(encodeURIComponent(tagName)+"="+encodeURIComponent(tagVal));                }else if(reg2.test(tagType)&&tag.checked){                    res.push(encodeURIComponent(tagName)+"="+encodeURIComponent(tagVal));                   }else if(reg3.test(tagType)){                    for(var j=0;j<tag.options.length;j++){                        if(tag.options[j].selected){                        res.push(encodeURIComponent(tagVal)+"="+encodeURIComponent(tag.options[j].value||tag.options[j].text));                          }                    }                }else{}            }              return res.join(" & ");        }                // 調用        var oForm = document.getElementById(‘target‘);        console.log(serializeForm3(oForm));

結果:

650) this.width=650;" src="https://s3.51cto.com/wyfs02/M02/9E/4C/wKiom1mNpbfTxYUzAAAbz3x3G20786.png" title="圖片1.png" alt="wKiom1mNpbfTxYUzAAAbz3x3G20786.png" />

js: 將 form表單序列化

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.