Function . click does not work on buttons that were dynamically generated by the . html function?

Asked

Viewed 707 times

2

I have the following code:

var nReqAJAX = nReqAR
$.ajax({
    type: "POST",
    url: "../controller/ajax.selectItemRequisicaoPesquisar.php",
    data: {'numeroRequisicao': nReqAJAX},
    dataType: "JSON",
    success: function(res) {
        if(res == null)
        {
            $('#modalReqInvalida').modal('show');
        }
        else
        {
            var html = res.reduce(function(string, obj, i) {
                return string + '<tr class="text-center"><td style="vertical-align: middle;">' + i + '</td><td style="vertical-align: middle;">' + obj.nome_GAThemocomponente + '</td><td style="vertical-align: middle;">' + obj.qtd_GATitemRequisicao + '</td><td style="vertical-align: middle;">' + obj.frequencia_GATitemRequisicao + '</td><td style="vertical-align: middle;">' + obj.cirurgia_GATitemRequisicao + '</td><td><button id="1" name="btnAtender" class="btn btn-success" style="width: 100%;">Atender Item</button></td></tr>'
            }, '');
            $("#tab_logic tbody").html(html);
        }
    }
});

$("button[name='btnAtender']").on(function(){
    alert('teste');
});

A AJAX when loading the page, if the return is null, I show a modal, if the result is not null, "drawing" a table using the function .html, so far so good, the problem is that when drawing the table, I draw also a button in the last cell and I say the name of this button is btnAtender, however, I would like to do the following function:

$("button[name='btnAtender']").click(function(){
    alert('teste');
});

That is, when the user clicks on button btnAtender, there’s gonna be a alert showing a text, but this simple function is not working, apparently because it is running when from the click of a dynamically generated button, for test effect, I created a <button name="btn">btn teste</button> page html and function worked.

What I could do to function the alert?

4 answers

2


Don’t do it this way:

$("button[name='btnAtender']").click(function(){
    alert('teste');
});

And yes this way:

$("button[name='btnAtender']").on('click', function(){
    alert('teste');
});

"This is basically how the association for the element is done. . click if applies to current DOM, while . on (using delegation) will continue for new elements added to the DOM after the association of the event."

Source: /questions/5196/qual-a-diferença-entre-o-onclick-function-e-o-clickfunction

  • 1

    Had chosen another answer as "correct", but this also worked and had an important mention to gain knowledge, since the link provided taught me things that I had not yet known. Thank you!

1

No, the DOM has already been rendered, but you can resolve by referencing the document

$(document).on('click', '#gerar', function(){
   $('body').append('<button id="gerado">Executar Alert</button>')
})

$(document).on('click', '#gerado', function(){
    alert('oi')
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="gerar">Gerar</button>

0

I’ll explain what happens. When you put this first code, the btnAtender button doesn’t exist yet. There are several ways to solve this, but what would solve quickly (and ugly) would be to put the code:

$("button[name='btnAtender']").on('click',function(){
    alert('teste');
});

just below this:

$("#tab_logic tbody").html(html);

That way the button will already be on the page when the click is associated.

Try it like this:

var nReqAJAX = nReqAR
$.ajax({
    type: "POST",
    url: "../controller/ajax.selectItemRequisicaoPesquisar.php",
    data: {'numeroRequisicao': nReqAJAX},
    dataType: "JSON",
    success: function(res) {
        if(res == null)
        {
            $('#modalReqInvalida').modal('show');
        }
        else
        {
            var html = res.reduce(function(string, obj, i) {
                return string + '<tr class="text-center"><td style="vertical-align: middle;">' + i + '</td><td style="vertical-align: middle;">' + obj.nome_GAThemocomponente + '</td><td style="vertical-align: middle;">' + obj.qtd_GATitemRequisicao + '</td><td style="vertical-align: middle;">' + obj.frequencia_GATitemRequisicao + '</td><td style="vertical-align: middle;">' + obj.cirurgia_GATitemRequisicao + '</td><td><button id="1" name="btnAtender" class="btn btn-success" style="width: 100%;">Atender Item</button></td></tr>'
            }, '');
            $("#tab_logic tbody").html(html);
            $("button[name='btnAtender']").on(function(){
               alert('teste');
            });
        }
    }
});
  • That’s not how the Event Listener works. See a quick example on codepen.io and see that a new one will always be added Event Listener on the existing button, and never on the added button.

  • Although it seems strange the answer, I was able to solve the problem, the only difference it had is that I used the function .click instead of .on As you mentioned, done so, it worked just as I wished. Maybe this isn’t the right way to do what I’d like, but since it’s just a college job, it meets my needs. Thank you.

0

Define a promisse, gets like this...

Set the click event as a function

function comp(){
    $("button[name='btnAtender']").on('click',function(){
        alert('teste');
    });
}

When placing the html

$("#tab_logic tbody").html(html).promise().done(function(){
    comp();
});

Your function will extend, so you won’t need to call the whole code again.

Browser other questions tagged

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