I'm struggling to implement a feature in my form that allows the user to add multiple entries, but I'm having trouble with the removal aspect.
Here is the JavaScript code:
var i = 1;
var divContent = document.getElementById('formulario');
//Click to add a field
function cria() {
//This adds HTML Inputs and divs with IDs based on the 'i' variable which increments
document.getElementById('formulario').innerHTML += '<div class="mb-1 col-3" id="div'+i+'"><label for="nomeTx0" class="form-label">Nome</label><input type="text" class="form-control" id="nomeTx'+i+'" name="nomeTx'+i+'" required></div><div class="mb-1 col-3" id="div2'+i+'"><label for="taxa'+i+'" class="form-label">Valor</label><input type="float" class="form-control" id="taxa'+i+'" name="taxa'+i+'" required></div><a href="#" data-id="1" onclick="remove(div'+i+',div2'+i+')" id="adicionarCampo">- Remover campo</a>';
i++;
}
function remove(div1, div2){
var div = document.getElementById(div1);
var div2 = document.getElementById(div2);
div.remove();
div2.remove();
i--;
}
And here is the corresponding HTML code:
<form>
<h4 class="card-tittle text-center">Taxas</h4>
<div id="formulario" class="form row align-items-start">
<div class="mb-1 col-3" id="0">
<label for="nomeTx0" class="form-label">Nome</label>
<input type="text" class="form-control" id="nomeTx0" name="nomeTx0" required>
</div>
<div class="mb-1 col-3" id="0">
<label for="taxa0" class="form-label">Valor</label>
<input type="float" class="form-control" id="taxa0" name="taxa0" required>
</div>
</div>
<a href="#" data-id="1" onclick="cria()" id="adicionarCampo">+ adicionar campo</a>
<div class="mb-1 col-lg-12" style="text-align: center;">
<button class="btn btn-primary col-5" id="Enviar" type="submit" text="Enviar">Adicionar Taxas</button>
</div>
</form>
The issue arises when using ID="taxa"+i and calling the remove() function, causing an error stating that the variable is null.