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 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。
  • ¥20 CST怎么把天线放在座椅环境中并仿真
  • ¥15 任务A:大数据平台搭建(容器环境)怎么做呢?
  • ¥15 YOLOv8obb获取边框坐标时报错AttributeError: 'NoneType' object has no attribute 'xywhr'