4
I now have the following code in jquery to add inputs according to the existing number in a text box,
However, if the form already exists for some field when clicking to add another one, all fields and their contents are deleted and new blank field is inserted,
It is possible when for example, the text box is in 5 and with the content filled I by clicking to add only one more or is a total 6 it just add and not delete those that already exist, and if you want to remove one it just delete the last entry?
Follow the code I have at the moment
$(document).ready(function() {
var $txtQuantidade = $('#txtQuantidade');
var $btnAdicionar = $('#btnAdicionar');
var $divForm = $('#divForm');
$btnAdicionar.on('click', function() {
var qtde = $txtQuantidade.val();
console.log(qtde);
var html = '';
for (var i = 0; i < qtde; i++) {
html += '<div>';
html += '<input type="date" id="txtData_' + i + '" name="data[]">';
html += '<input type="time" id="txtHoraIni_' + i + '" name="hinicio[]">'
html += '<input type="time" id="txtHoraFim_' + i + '" name="hfim[]">';
html += '<div>';
}
$divForm.html(html);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="txtQuantidade" />
<input type="button" id="btnAdicionar" value="Adicionar" />
<div id="divForm"></div>
The method
.html()
overwrite everything in the object context. Use the method.append()
.– Daniel Omine
Recommended reading http://www.linhadecodigo.com.br/artigo/3499/trabando-insercao-de-conteudo-com-jquery.aspx
– Wallace Maxters