1

Help, I have a function that changes the index, I would like the fields to be added to a new div and the last div deleted.

const addActivity = (parent, arr, name) => {
    const el = $(parent).find(`input[name^="${arr}"]`).last();
    const attr = el.attr('name');
    const index = +attr.match(/(?<=\[).+?(?=\])/)[0];
    const newEl = el.clone();
    newEl.attr('name', `${arr}[${index + 1}][${name}]`);
    $(parent).append(newEl);
}

    $('#addField').click(() => {
    addActivity('.first', 'activity','first');
    addActivity('.first', 'term','last');
    addActivity('.last', 'activity1','first1');
    addActivity('.last', 'term1','last1');
    
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class ="first">
    <input type="text" id="parent" value="div" name="activity[0][first]">
    <input type="text" id="name" value="activity" name="term[0][last]">
</div>
<div class ="last">
    <input type="text" id="parent1" value="div1" name="activity1[0][first1]">
    <input type="text" id="name1" value="activity1" name="term1[0][last1]">
</div>
<button id="addField">Add</button>
Levash
  • 13
  • 5

1 Answers1

2

You dont need index's, its already there since you have the name="phoneNumber[]" as array.

Try:

const addActivity = (parent, name) => {
    const firstRow = $(parent).first();
    const lastRow = $(parent).last();
    const newRow = firstRow.clone()
    newRow.find('input').val('');
    newRow.append('<input type="button" class="btnRemove" value="Remove"/>');
    lastRow.after(newRow);
}

dont forget to chane the name="phoneNumber[]"

<input type="text" name="phoneNumber[]" />
SoftViruS
  • 119
  • 4
  • will I lose the data in the array? will people[]first = people[]phone. Thanks for the help. http://jsfiddle.net/nvk956wy/3/. – Levash Jan 16 '22 at 10:03
  • you want to add new phones only? or new full group for new people? – SoftViruS Jan 16 '22 at 10:24
  • it seems I let you astray, I corrected my question. I need a new full group for new people. excuse me – Levash Jan 16 '22 at 11:04