Adding inputs in jquery, but not deleting the ones that already exist

4

I am currently having the following code in jquery to add inputs according to the number in a text box,

However if the form already exists for some field when clicking to add another one is deleted all fields and their content and inserted new blank field,

It is possible when, for example, the text box is at 5 and with the content filled in I click to add just one or a total 6 it just add and do not delete those that already exist, and if you want to remove a it just delete the last entry?

Follow the code I have right now

$(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><inputtype="text" id="txtQuantidade" />
<input type="button" id="btnAdicionar" value="Adicionar" />
<div id="divForm"></div>
    
asked by anonymous 09.12.2015 / 13:23

2 answers

5

Use append instead of html

$divForm.append(html);

The append is used to add elements or texts at the end of the content of the target element.

If you want to do the opposite, that is, put at the beginning of the target element, use the function prepend .

    
09.12.2015 / 13:26
4

Good morning, my friend, in jQuery has the following functions

html() - $divForm.html('......') : This function overwrites all content within the element and inserts the contents passed in the parameter.

append() - $divForm.append('......') : This function adds content passed as a parameter after the element that is present inside the div or another element captured in the selector.

prepend() - $divForm.prepend('......') : This function adds content passed as a parameter at the beginning of the div or another element captured in the selector.

It has the function appendTo() also that inserts elements inside a selector, but in a reverse way to append() , example $('........').appendTo($divForm);

    
09.12.2015 / 13:38