0

I have an area on my website that I allow users to update their profile information.

html

<div class="my-class">
    <input type="text" name="fields[myFieldHandle][1][fields][firstName]" value="">
    <button type="button" id="add">Add Another</button>
</div>

jquery

$('#add').click(function (event) {
    $('.my-class').clone().insertAfter('div.my-class');
});

All is well, I am able to clone the text input. However, I need to be able to increment the [1] value by one. I could try matching the string, but I feel that is assuming quite a bit. Is there a more effective way to clone this:

<input type="text" name="fields[myFieldHandle][1][fields][firstName]" value="">

to this:

<input type="text" name="fields[myFieldHandle][2][fields][firstName]" value="">

jsFiddle

1 Answer 1

1

Instead of cloning the first div, clone the last one so you'll get the last input.

You can then increment its number as follows:

$('#add').click(function (event) {
  $('.my-class:last')
    .clone()
    .insertAfter('div.my-class:last')
    .find('input')                                       //get the input
    .attr('name', function(_, currentValue) {            //get its current value
      return currentValue.replace(/\d/, function(num) {  //replace the numeric part
        return +num + 1;                                 //with its value + 1
      });
    });
});

Fiddle

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.