dtwncxs3547 2018-09-03 16:59
浏览 77
已采纳

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

I have a form, i have dynamically added inputs, i have change index of each input when it is added dynamically.

Here is my html form.

$(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>

Here is my script code.

</div>
  • 写回答

1条回答 默认 最新

  • duanqiao1926 2018-09-03 17:10
    关注

    Target the last input in each click:

    Change

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

    To

    $('input.hobies').last().attr('name', "hobies["+hobiesIndex+"]");
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Pwm双极模式H桥驱动控制电机
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题