2
I am working on a form with dynamically inserted fields. But I want the fields to be inserted only if they don’t exist yet. My html:
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="utf-8">
<title>Testando</title>
</head>
<body>
<p>Milho <input type="checkbox" class="check"> </p>
<p>Sorgo <input type="checkbox" class="check"> </p>
<p>Monenzina <input type="checkbox" class="check"> </p>
<p>Calcário Calcítico <input type="checkbox" class="check"> </p>
<p>Farelo de Soja <input type="checkbox" class="check"> </p>
<p>Farelo de Algodão <input type="checkbox" class="check"> </p>
<p>Aromatizante <input type="checkbox" class="check"> </p>
<p>Farelo de Arroz <input type="checkbox" class="check"> </p>
<button id="add-button" type="submit">Adicionar</button>
<div id="receiver">
<form id="form-receiver">
<fieldset>
</fieldset>
</form>
</div>
</body>
My javascript:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$('#add-button').click(function(){
$('.check').each(function(){
if($(this).is(':checked')){
$('#form-receiver fieldset').append("<p>" +$(this).parent().text()+ "<input name='" + $(this).parent().text().toLowerCase() + "'></p>")
}
})
});
</script>
So the insertion works perfectly. However, it is possible for repeated fields to be added if the user decides to mark more checkboxes and click the add button. Should be added only if there are no.
I tried it this way:
$('#add-button').click(function(){
$('.check').each(function(){
if($(this).is(':checked')){
if(!$('#form-receiver').has("input[name='" $(this).parent().text().toLowerCase() "']"){
$('#form-receiver fieldset').append("<p>" +$(this).parent().text()+ "<input name='" + $(this).parent().text().toLowerCase() + "'></p>")
}
}
})
});
But it hasn’t worked yet. Could someone help here? : D
Man!! Thanks a lot! I had not even considered this possibility! Solved my problem. Thank you very, very much! ;-)
– Pedro Vinícius
Have @Pedrovinícius implement also the solution of the friend there referring to the names of the field, a great hug and good luck with the projects.
– Diego Vieira