0

I have a set of inputs which can be duplicated, but I then need to increment the array value of them. How do I do this?

<input type="text" name="person[0][name]">
<input type="text" name="person[0][age]">

This can then be duplicated, but I need to change the new inputs to be like:

<input type="text" name="person[1][name]">
<input type="text" name="person[1][age]">

I have got so far:

cloned.find('input, select').each(function(){
    var $this = $(this);

    $this.attr('name',
        $this.attr('name').match(/\[\d+]/g, '[' + what_goes_here + ']')
    );
});

Where cloned is my last group of inputs.

What do I do with the value of what_goes_here?

Ryan Hipkiss
  • 648
  • 1
  • 7
  • 20
  • Use `replace` with captured group. `$this.attr('name', function(i, name) { return name.replace(/\[(\d+)]/g, function(m, $1) { return '[' + (Number($1) + 1) + ']'; }); });` – Tushar Feb 06 '17 at 09:59
  • Are the elements both cloned and possibly later removed from `document`? – guest271314 Feb 06 '17 at 10:01
  • No, can't be removed from document, Only the last element is cloned and then incremented. – Ryan Hipkiss Feb 06 '17 at 10:07
  • I think http://stackoverflow.com/questions/1912536/how-can-i-increment-a-number-matched-via-regex will help you. – Vijay Maheriya Feb 06 '17 at 10:10

1 Answers1

0

You can use .match() with RegExp \d+, + operator, .replace()

cloned.find('input, select').each(function() {
    var $this = $(this);
    var n = $this.attr('name').match(/\d+/)[0];
    $this.attr('name', $this.attr('name').replace(n, +n + 1));
});
guest271314
  • 1
  • 15
  • 104
  • 177