- Don't use IDs for your duplicated elements.
- Don't use inline JS
on*
handlers attributes. Same as you hopefully don't use inline CSS style
attribute.
- To get a count of your current elements you could use
.children().length
const
$inputs = $("#inputs"),
$add = $("#add"),
$send = $("#send"),
$data = $("#data");
function add() {
const n = $inputs.children().length + 1;
$inputs.append(`<div><input type="text" name="name_${n}"></div>`);
}
function send() {
const data = $inputs.find('[name^="name_"]').get().map(el => el.value);
$data.append(data.join("<br>"));
}
$add.on("click", add);
$send.on("click", send);
add(); // Init! (Add the first input)
<div id="inputs"></div>
<button type="button" id="add">+ Add</button>
<button type="button" id="send">→ Send</button>
<div id="data"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…