Why is my append (jQuery) duplicating elements?

Asked

Viewed 222 times

-1

Good morning.

I have the following code.

// Inclui novo Container com seus elementos
$(document).on('click', 'ul[class^="inpt_"] li button[name="mais"]', function () {
    var i = 0;
    $('#gado ul[class^="inpt_"]').each(function () {
        var alvo = $(this).attr('class');
        alvo = alvo.replace('inpt_', '');
        alvo = parseInt(alvo, 10);
        if (alvo > i) {
            // Serve apenas para ver qual o elemento com maior número
            i = alvo;
        }
    });
    i++;

    $('#gado').append(
            "<div>" +
            "<ul class='inpt_" + i + "'>" +
            "<li><input name='boi[]' type='text' maxlength='50' placeholder='Num. do animal'></li>" +
            "<li><select class=\"verificar\" name='fk_boi[]'><option value=''>Aguardando...</option></select></li>" +
            "<li><input class=\"verificar\" type='number' name='peso[]' placeholder='Peso'></li>" +
            "<li><input class=\"verificar\" type='date' name='d_peso[]'></li>" +
            "<li><button type='button' name='mais'>+1</button></li>" +
            "<li><button type='button' name='inpt_" + i + "'>excluir este</button></li>" +
            "</ul>" +
            "<div class='cboth'></div>" +
            "</div>"
            );
});

Initially it creates a single element, but doubles the amount each time the dialog window it is connected to opens. The second time he adds two of the same, the third time the window opens he creates three/four and so it goes.

If I clear the browser cache, it goes back to normal, but I can’t keep asking the client for it.

Any hint of what might be wrong?

1 answer

0

Hello,

From a read in jQuery documentation on the functions append and html. The function append() add the content after the last element, already the function html() sets the contents of the element as the one passed by parameter. See:

var elemento = "<i>teste</i>";

$("body").append(elemento); // <i>teste</i>
$("body").append(elemento); // <i>teste</i><i>teste</i>
$("body").append(elemento); // <i>teste</i><i>teste</i><i>teste</i>

$("body").html(elemento); // <i>teste</i>

So what your code is doing is adding a new div to the end of the content every time you run the function. Change the append to html and your code will work.

I hope I helped, hug!

  • Good afternoon, @Lucas Deano. Thank you for sharing your knowledge. In my case, I need to add that element to the end. O . html does not solve me. It is a sales form where the user adds products as needed.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.