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