【问题标题】:why closest index of input name from dynamically added input not working?为什么动态添加的输入中最接近的输入名称索引不起作用?
【发布时间】:2019-02-08 18:01:15
【问题描述】:

我有一个表单,我动态添加了输入,当动态添加每个输入时,我都有更改索引。

这是我的 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】:

在每次点击中定位最后一个input

改变

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

$('input.hobies').last().attr('name', "hobies["+hobiesIndex+"]");

【讨论】:

  • 感谢您的回答,正是我在寻找它,我不想在我想最后使用的时候使用
  • @Sai,不客气。选择器没有针对代码中的正确元素.....
猜你喜欢
  • 2011-04-03
  • 1970-01-01
  • 1970-01-01
  • 2020-03-25
  • 1970-01-01
  • 1970-01-01
  • 2019-03-16
  • 2014-03-19
  • 2018-02-28
相关资源
最近更新 更多