您好,登錄后才能下訂單哦!
這篇文章給大家分享的是有關(guān)怎么利用JS獲取form表單數(shù)據(jù)的內(nèi)容。小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,一起跟隨小編過來看看吧。
方法如下:
1.有的時(shí)候想偷點(diǎn)懶,頁面上有大量的表單提交數(shù)據(jù),每次單獨(dú)獲取都比較麻煩。代碼冗余度也比較多,因此封裝了一個(gè)方法。
2. 表單元素必須要有name屬性,name屬性是向后端提交的字段數(shù)據(jù)。
3.html代碼
<h4>下拉框</h4> <select name="sel" id="sel" class="query"> <option value ="sel-1">sel-1</option> <option value ="sel-2">sel-2</option> </select> <h4>輸入框</h4> <input type="text" name="text1" class="query" value="hello" /> <input type="text" name="text2" class="query" value="word" /> <h4>密碼框</h4> <input type="password" name="password" class="query" value="123456" /> <h4>單選框</h4> 單選1<input type="radio" name="radio" class="query" value="r1" checked /> 單選2<input type="radio" name="radio" class="query" value="r2" checked/> 單選3<input type="radio" name="radio" class="query" value="r3" /> <h4>復(fù)選框</h4> 復(fù)選框1<input type="checkbox" name="check" id="" class="query" value="c1" checked/> 復(fù)選框2<input type="checkbox" name="check" id="" class="query" value="c2" /> 復(fù)選框3<input type="checkbox" name="check" id="" class="query" value="c3" checked/> <h4>search</h4> <input type="range" name="range" id="" class="query" value="" /> <input type="color" name="color" id="" class="query" value="" /> <h4> <button type="button" id="save"> 提交 </button> </h4>
4.此處引入了JQ庫。
4.1js代碼塊
使用說明:調(diào)用方法的時(shí)候傳入class名稱即可。
// 封裝方法,獲取到form表單的數(shù)據(jù)。使用此方法,表單元素必須存在那么屬性。 //el:元素的class名稱。 function getParameter(el){ var obj={}; $(el).each(function(index,item){ // 判斷元素的類型 if(item.type=="text" || item.type=="password" || item.type=="select-one" || item.type=="tel" || item.type=="search" || item.type=="range" || item.type=="number" || item.type=="month" || item.type=="email" || item.type=="datetime-local" || item.type=="datetime" || item.type=="date" || item.type=="color"){ //獲取到name的值,name的值就是向后臺(tái)傳遞的數(shù)據(jù) obj[$(this).attr("name")]=$(this).val(); }else if(item.type=="checkbox"){ var stamp=false; if($(this).attr("name") && !stamp){ stamp=false; // 獲取到復(fù)選框選中的元素 var checkboxEl=$("input[name="+$(item).attr('name')+"]:checked"); if(checkboxEl){ var checkboxArr=[]; // 取出復(fù)選框選中的值 checkboxEl.each(function(idx,itm){ checkboxArr.push($(itm).val()); }); obj[$(this).attr("name")]=checkboxArr.join(","); } } }else if(item.type=="radio"){ // 獲取到單選框選中的值 var radio_val=$("input[name="+$(item).attr('name')+"]:checked").val(); if(radio_val){ obj[$(item).attr("name")]=radio_val; } } }); return obj; } // 調(diào)用方法 $("#save").click(function(){ var parameter=getParameter(".query"); console.log(parameter); });
感謝各位的閱讀!關(guān)于“怎么利用JS獲取form表單數(shù)據(jù)”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,讓大家可以學(xué)到更多知識(shí),如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到吧!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。