1. 程式人生 > >獲取表單內的所有元素的值 表單格式化外掛jquery.serializeJSON

獲取表單內的所有元素的值 表單格式化外掛jquery.serializeJSON

簡單描述:一個form表單裡有十幾個input或者select,要獲取到他們的值,我的做法一直都是$("#id").val();這樣做本來沒什麼說的,但是如果有很多呢,就很麻煩,看了同事的一段程式碼,很亮眼(其實 是我菜 ヾ(◍°∇°◍)ノ゙,沒見過這種寫法)

簡介:序列化form表單的資料成JS物件。

程式碼:

//需要引入的jar包 任意一個都可以
<
script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="jquery.serializejson.js"
></script>
//html程式碼 
<form action="" class="horizontal-form" method="post" id="addForm" autocomplete="off" onSubmit="return false" enctype="multipart/form-data"> <input hidden="hidden" type="text" id="planStatus" name="planStatus"/> <input type="text" id="planName" name="planName" class="form-control" th:value="${plan?.planName}" placeholder="請輸入名稱" maxlength="50"/> <input type="text" id="planCode" value="根據系統編碼規則自動生成" disabled="disabled" name="planCode" class="form-control" placeholder="自動生成" maxlength="50"/> <select id="orgName" class="form-control" placeholder="請選擇管理機構"> <option th:each="org : ${orgs}" th:value="${org.orgId}" th:text="${org.orgName}" xmlns:th="http://www.w3.org/1999/xhtml">
      </option> </select> <select id="isOpen" name="isOpen" class="form-control js-example-basic-single" placeholder="開放使用"> <option value="0" selected="selected">不開放</option> <option value="1">開放</option> </select> <div class="col-md-6"> <label class="control-label flex" style="margin-top: 10px;"> 上傳圖示<span class="star align-items">*</span> </label> <img th:src="@{/assets-new/apps/img/shangchuan.png}" id="imgPlanIcon" width="35px" height="35px"/> <input type="file" id="seledIcon" style="display:none"/> </div> <input type="hidden" name="planIcon" th:value="${plan?.planIcon}" id="planIcon"/> <textarea id="planDesc" name="planDesc" class="form-control" placeholder="請填寫描述資訊" th:text="${plan?.planDesc}" maxlength="200">
         </textarea> <input type="text" oninput="clearNoNum(this)" id="sellPrice" name="sellPrice" class="form-control" placeholder="請輸入銷售價" th:value="${plan?.sellPrice}" maxlength="50"/> </form>
//js程式碼 var planJson = JSON.stringify($("#addForm").serializeJson());
//說明一下:$("#addForm").serializeJson() 就是把form中所有的元素序列化成為一個數據物件,名值對的形式
//JSON.stringify()是將一個javascript的值(物件或陣列)轉換成一個json字串,可以傳遞給後臺,後臺通過getParameter("planJson")取值

總結:就是通過使用serializeJson()來完成js物件的封裝