Marc_78
Marc_78

Reputation: 59

Changing a part of name from a input field with jquery

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.

Upvotes: 1

Views: 60

Answers (1)

Swati
Swati

Reputation: 28522

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>

Upvotes: 1

Related Questions