I have a web application that I made a simple forms to store values of a patchpanel and I made a dynamic input that when saying how many ports that patch has, automatically generate new fields, eg I filled out that the patch has 5 ports , so below it it generates the 5 fields to fill what each port is connected to. The problem is that if you do this and start filling in the fields it already saved normal, the problem is that if the user for some reason wants to increase or decrease the number of ports and already filled some fields, in this change of ports qtd fields will be cleaned.
InoticedthatIneededtochangethevalueoftheports,Iwant1moreports.Iadd,butcleanallfilledfields thisisnotinterestingthathappensinthesystem,soIlookforawaytosavethedatawhiletheusercanchangethenumberofports.
<form><divclass="form-group">
<label>Número de portas:</label> <input id="numporta" type="number"
name="patchpanel.numPortas" class="form-control"
value="${flash['patchpanel.numPortas'] ? flash['patchpanel.numPortas'] : p?.numPortas}" onchange="geraAlerta(this.value)">
<span class="alert-danger">#{error 'patchpanel.numPortas' /}</span>
</div>
<div class="inputs">
<label for="quantidade">Porta 1</label> <a href="javascript:void(0)" id="adicionarcampo"></a><br>
<input type="text" name="portas[0]" placeholder="Informe o equipamento contectado a porta" class="form-control" value="${flash['portas.descricao'] ? flash['portas.descricao'] : p?.descricao}"/>
</div><br>
</div>
<div class="col-lg-6">
<div class="form-group">
<label>Endereço IP:</label> <input type="text" name="patchpanel.ip"
class="form-control"
value="${flash['patchpanel.ip'] ? flash['patchpanel.ip'] : p?.ip}">
<span class="alert-danger">#{error 'patchpanel.ip' /}</span>
</div>
</form>
My JS is:
'var wrapper = $(".inputs");
var add_button = $("#adicionarcampo");
var x = 1;
function geraAlerta(max_fields){
//alert("Funfou porra!")
$(wrapper).html("")
for(x=0; x < max_fields; x++){
$(wrapper).append('<div><label>Porta '+ (x+1) +'</label><input type="text" name="portas['+ x +']"class="form-control" placeholder="Informe o equipamento contectado a porta" /></div>');
}
}
$(document).ready(function(){
$(add_button).click(function(e) {
e.preventDefault();
var length = wrapper.find("input:text.textAdded").length;
});
$(wrapper).on("click", ".remove_field", function(e) {
e.preventDefault();
$(this).parent('div').remove();
x--;
});'
});