jQuery實現點擊行選中或取消CheckBox的方法
642
2024-02-23
本文實例講述了jQuery實現form表單元素序列化為json對象的方法。分享給大家供大家參考,具體如下:
這段代碼序列化form表單元素為json對象:
<!Doctype html> <html xmlns=http://www.w3.org/1999/xhtml> <head> <title>jQuery擴展——form序列化到json對象</title> <meta http-equiv=Content-Type content="text/html;charset=utf-8"> <script type="text/javascript" src="http://www.gimoo.net/t/1904/jquery-1.10.2.js"></script> </head> <body> <p id="results"><b>Results:</b> </p> <form> <select name="aModel.single"> <option>Single</option> <option selected>Single2</option> </select> <br/><br/> <select name="aModel.multiple" multiple="multiple"> <option selected="selected">Multiple</option> <option>Multiple2</option> <option selected="selected">Multiple3</option> </select> <br/><br/> <input type="checkbox" name="aModel.check" value="check1"/> check1 <input type="checkbox" name="aModel.check" value="check2" checked="checked"/> check2 <br/><br/> <input type="radio" name="aModel.radio" value="radio1" checked="checked"/> radio1 <input type="radio" name="aModel.radio" value="radio2"/> radio2 </form> <script type="text/javascript"> var fields = $("select, :radio").serializeArray(); var o={}; jQuery.each(fields, function(i, fields){ if(o[this.name]){ /* 表單中可能有多個相同標簽,比如有多個label, 那么你在json對象o中插入第一個label后,還要繼續插入, 那么這時候o[label]在o中就已經存在,所以你要把o[label]做嵌套數組處理 */ //如果o[label]不是嵌套在數組中 if(!o[this.name].push){ o[this.name]=[o[this.name]]; // 將o[label]初始為嵌套數組,如o={a,[a,b,c]} } o[this.name].push(this.value || ''); // 將值插入o[label] }else{ o[this.name]=this.value || ''; // 第一次在o中插入o[label] } }); $("#results").append(JSON.stringify(o)); console.log(o); //用FireBug輸出 </script> </body> </html>
結果如下圖所示:
希望本文所述對大家jQuery程序設計有所幫助。
#免責聲明#
本站[綠夏技術導航]提供的一切軟件、教程和內容信息僅限用于學習和研究目的;不得將上述內容用于商業或者非法用途,否則,一切后果請用戶自負。本站信息來自網絡收集整理,版權爭議與本站無關。您必須在下載后的24個小時之內,從您的電腦或手機中徹底刪除上述內容。如果您喜歡該程序或內容,請支持正版,購買注冊,得到更好的正版服務。我們非常重視版權問題,如有侵權請郵件[admin@lxwl520.com]與我們聯系進行刪除處理。敬請諒解!