Thymeleaf中的动态行添加/删除

时间:2018-11-09 02:26:10

标签: json spring spring-mvc thymeleaf

我已经使用jquery在thymeleaf中实现了动态行添加/删除。但是我无法将行值捕获为json对象数组。

$(function(){      
         $('#addMore').on('click', function() {          
             var data = $("#tab_logic tr:eq(1)").clone(true).appendTo("#tab_logic");
             data.find("input").val('');
    });
    $(document).on('click', '.remove', function() {
        var trIndex = $(this).closest("tr").index();
           if(trIndex>1) {
            $(this).closest("tr").remove();
          } 
     });

要添加/删除动态行的表如下:-

<table class="table table-bordered table-hover" id="tab_logic">
<tr class="tr-header">
<label for="requestno">Sales target</label>
    <th>Team lead</th>
    <th>Sales volume</th>
    <th><a href="javascript:void(0);"
        style="font-size: 18px;" id="addMore"> <span
            class="glyphicon glyphicon-plus"></span></a></th>
</tr>
<tr>
    <td>
    <input  type="text" name="teamLead"  class="form-control" ></input>
    </td>
    <td>
    <input  type="text" name="salesVolume"  class="form-control" ></input>
    </td>
    <td>
    <a href='javascript:void(0);' class='remove'><span
            class='glyphicon glyphicon-remove'></span></a>
    </td>
</tr>

</table>

1 个答案:

答案 0 :(得分:0)

您可以使用serialize()函数序列化表单输入。这将返回一个查询字符串,然后可以使用JSON.stringify()将其转换为JSON对象。因此,我的建议是将所有内容添加到表单中,然后对其进行序列化。

HTML

<table class="table table-bordered table-hover" id="tab_logic">
<tr class="tr-header">
<label for="requestno">Sales target</label>
    <th>Team lead</th>
    <th>Sales volume</th>
    <th><a href="javascript:void(0);"
        style="font-size: 18px;" id="addMore"> <span
            class="glyphicon glyphicon-plus"></span></a></th>
</tr>
<form id="myForm>
<tr>
    <td>
    <input  type="text" name="teamLead"  class="form-control" ></input>
    </td>
    <td>
    <input  type="text" name="salesVolume"  class="form-control" ></input>
    </td>
    <td>
    <a href='javascript:void(0);' class='remove'><span
            class='glyphicon glyphicon-remove'></span></a>
    </td>
</tr>
</form>
</table>

Javascript / jQuery

$(function(){      
     $('#addMore').on('click', function() {
         // Add the row to your form, not the table.          
         var data = $("#tab_logic tr:eq(1)").clone(true).appendTo("#myForm");
         data.find("input").val('');
});

$(document).on('click', '.remove', function() {
    var trIndex = $(this).closest("tr").index();
       if(trIndex>1) {
        $(this).closest("tr").remove();
      } 
 });

 // Method that will generate the JSON object.
 function toJSON() {
     var data = $('#myForm').serialize();
     console.log(JSON.stringify(data));
 }