Adding, deleting jquery fields
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>
Solution 1:
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[]" />