jQuery動態生成input填寫時間值並且提交給後端
- 2019 年 10 月 8 日
- 筆記
今天寫的一個demo,關於jQuery動態生成input填寫時間值並且提交給後端。
需求:1:點擊新增按鈕的時候,會無限動態生成input輸入框,可以輸入不同的時間。 2:點擊提交按鈕的時候,將生成的這些時間提交到後端。
參考代碼如下所示:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>動態生成時間並且提交給後端</title> <script src="http://code.jquery.com/jquery-1.8.0.min.js"></script> </head> <body> <div class="form-group"> <label class="col-md-4 col-sm-4 col-xs-4 control-label">巡更時間 <em style="color: red;">*</em> </label> <div class="col-md-8 col-sm-8 col-xs-8"> <input type="text" class="form-control beginTime" name="stime" id="" value="09:00"></input> <input type="text" class="form-control endTime" name="etime" id="" value="17:00"></input> </div> </div> <div id="timeCont"></div> <div class="row " id="addtimebtn"> <div class="col-md-12 col-sm-12 col-xs-12"> <button type="button" id="fatBtn">新增</button> </div> </div> <button type="submit" id="addBtn">提交</button> </body> <script> /* 新增檢測時間 */ $("#fatBtn").click(function() { var htm = ""; htm += " <div class='form-group'>"; htm += "<label class='col-md-4 col-sm-4 col-xs-4 control-label'>巡更時間<em style='color: red;'>*</em></label>"; htm += "<div class='col-md-8 col-sm-8 col-xs-8'>"; htm += "<input type='text' class='form-control beginTime' name='stime' value='09:00'></input>"; htm += "<input type='text' class='form-control endTime' name='etime' value='17:00'></input></div></div>"; $('#timeCont').append(htm); }); $("#addBtn").on("click", function() { var params = { times: getTimes(), } alert(JSON.stringify(params)) $.ajax({ url: "", contentType: 'application/json', data: JSON.stringify(params), type: "POST", success: function(data) { } }); }) //獲取時間周期 function getTimes() { var times = new Array(); //創建list集合 $("input[name='stime']").each(function(i, value) { var obj = {}; obj.stime = $(this).val(); times.push(obj); }); $("input[name='etime']").each(function(i, value) { times[i].etime = $(this).val(); }); return times; } </script> </html>
原文作者:祈澈姑娘 技術博客:https://www.jianshu.com/u/05f416aefbe1