首页 > 解决方案 > 使用 jquery 从输入字段更改名称的一部分

问题描述

我试图将行动态添加到表中。我已经克隆了最后添加的行。在每个新行上,输入字段的名称应该用一个数字重命名+1。为此,我想重命名输入字段,但我没有这样做。

    Original row
    <input type="text" name="myfiels[0]" value="mytext">
First clone row
<input type="text" name="myfiels[1]" value="mytext">
Second clone row
<input type="text" name="myfiels[]" value="mytext">
...


$trNew.find('[name]').each(function () {
                    var num = this.name.replace(/\D/g, '');
                    if (!num) {num = 0;}

                    // Remove numbers by first regexp
                    // increment number
                    //this.name = this.name.replace(/\d/g, '') + (1 + parseInt(num, 10));

                    this.name.replace(/[.+]/,"["+(1 + parseInt(num, 10))+"]");                       
                });

我认为regex是错误的。

标签: jquery

解决方案


您可以使用一些变量 ie :count它将保存下一个要添加的值name,当您循环遍历每个输入时,您可以获得名称input并将其替换为新名称 ie :name+"["+count+"]"然后将计数增加1.

演示代码

var count = 0;//delcare this
$("div").find('input').each(function() {
var name = $(this).attr("name");//get name of input field
 $(this).attr("name", name +"[" + count + "]");//add new name
  count++;//increment

});

function namess() {
  $("div").find('input').each(function() {
    console.log($(this).attr("name"));
  });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Original row
<div>
  <input type="text" name="myfiels" value="mytext"> First clone row
  <input type="text" name="myfiels" value="mytext"> Second clone row
  <input type="text" name="myfiels" value="mytext"> ...
</div>
<button onclick="namess()">Click me to get names</button>


推荐阅读