1

I tried to add rows dynamically to a table. I have cloned the last added row. On every new row the name of the input field should rename with a number +1. For this, I wanted to rename the input fields, but I failed to do it in this way.

    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))+"]");                       
                });

I think the regex is wrong.

1 Answer 1

1

You can use some variable i.e : count which will hold next value to add in name and when you loop through each input you can get the name of input and replace it with new name ie : name+"["+count+"]" and then increment the count by 1.

Demo Code :

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.