为什么动态添加输入的输入名称的最近索引不起作用?

问题描述 投票:0回答:1

我有一个表单,我有动态添加输入,我有动态添加每个输入的更改索引。

这是我的html表单。

$(function(){
  var hobiesIndex = 1;
  $("#add_field").click(function () {
    $(this).closest('tr').find('input.hobies').attr('name', "hobies['"+hobiesIndex+"']");
    $("#table_container").append($("#temp_div").html());
    hobiesIndex++;
  });
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form action="" method="POST" enctype="multipart/form-data"> 
  <table id="table_container">
  <tr>
      <th><label class="lbl-header">My Hobies</label></th>
      <th><label class="lbl-header">Image</label></th>
  </tr>
  <tr>
    <td><input type="text" class="hobies" name="hobies[0]" value=""></td>
    <td>
            <input id="file-input" class="imgInp"  type="file" name="image[0]" />
    </td>
  </tr>
 </table>
   <p class="contact">
      <a class="button" id="add_field"><span style="text-transform: uppercase;"> + Add More</span></a>
  </p>
  <input type="submit" name="submit" value="Submit">
</form>
 <table class="product_sku_input"  id="temp_div" style="display: none">
  <tr>
     <td><input type="text" class="hobies" name="hobies[]" /></td>
     <td>     
  <input id="file-input" class="imgInp" type="file" name="image[]" />
     </td>
  </tr>
</table>

这是我的脚本代码。

javascript php jquery html dynamic
1个回答
0
投票

定位每次点击的最后一个input

更改

$(this).closest('tr').find('input.hobies').attr('name', "hobies['"+hobiesIndex+"']");

$('input.hobies').last().attr('name', "hobies["+hobiesIndex+"]");
© www.soinside.com 2019 - 2024. All rights reserved.