I'm working on a form with dynamically inserted fields. But I want fields to be inserted only if they do not already exist. 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-receiverfieldset').append("<p>" +$(this).parent().text()+ "<input name='" + $(this).parent().text().toLowerCase() + "'></p>")
}
})
});
</script>
So the insert works perfectly. However, it is possible that repeated fields are added if the user decides to mark more checkboxes and click the add button. They should be added only if they do not exist.
I tried the following:
$('#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 still did not work. Could someone help here? : D