Run Javascript function in event by clicking a button inside a table

Asked

Viewed 14,405 times

3

Good morning, I have a table and in each row of this table I have a button, when I click this button I need to run a function but I’m not able to do it because I think I don’t know how to use the correct selectors.

Table:

<table id="tbl" class="table table-striped">
    <tr id="cabecalho">
        <th>
            ID
        </th>
        <th>
            Insumo
        </th>
        <th>
            TD
        </th>
        <th>
            Unidade
        </th>
        <th>
            Quantidade
        </th>
        <th>
            Adicionar
        </th>
    </tr>
</table>

Script that generates the table body:

$('#pesquisar').click(function () {
    $('.corpoTbl').remove();
    $.ajax({
        url: "/RCM/ListarMateriais",
        type: "POST",
        data: { nome: $('#NomeMaterial').val() },
        datatype: 'json',
        success: function (data) {
            $.each(data, function (I, item) {
                $('#tbl').append("<tr class=\"corpoTbl\"> <td class=\"id\">" + item.ID + "</td><td>" + item.Nome + "</td><td>" + item.TD + "</td><td>" + item.Unidade +
                    "</td><td> <input class=\"qtda\" type=\"text\" value=\"0\" style=\"width: 50px;\" /> </td><td> <input class=\"btn\" type=\"button\" value=\"Adicionar\" /> </td></tr>")
            })
        }
    });
});

Script I want to run at the click of the button.

$('#tbl .btn').click(function () {
    var Qtd = $('.qtda');
    var Id = $('.id');    
    if (Qtd.value != "0" && Qtd.value != "") {
        $.ajax({
            url: "/RCM/AddMaterial",
            type: "POST",
            data: { "Qtd": $('.qtda').Value, "Id": Id.textContent }
        })
        alert("Materiais Adicionados!");
    }
    else {
        alert("Informe a quantidade do material!")
    }

})

2 answers

8


The problem seems to me that you are trying to find the buttons to wait for clicks before the buttons exist on the page, since they are added later, via ajax.

The simplest solution would be to use delegated events, where you will wait for clicks on the table, as it is already on the page from the beginning, filtering for only clicks that come from buttons:

$('#tbl').on('click', '.btn', function (event) {
    var $botao = $(event.target);
    var $tr = $botao.closest('tr');
    var $qtda = $tr.find('.qtda');
    var $id = $tr.find('.id');    
    if ($qtda.val() !== "0" && $qtda.val() !== "") {
        $.ajax({
            url: "/RCM/AddMaterial",
            type: "POST",
            data: { "Qtd": $qtda.val(), "Id": $id.text() }
        })
        alert("Materiais Adicionados!");
    }
    else {
        alert("Informe a quantidade do material!")
    }

})
  • It worked out, I really think that’s what you said, I never thought about it, thank you very much.

0

It seems to be all right. Have you run some debug tests? If not, try:

console.log("nbtn = " + $('#tbl .btn').length);

$('#tbl .btn').click(function () {

    alert("ok");

    var Qtd = $('.qtda');
    var Id = $('.id');    
    if (Qtd.value != "0" && Qtd.value != "") {
        $.ajax({
            url: "/RCM/AddMaterial",
            type: "POST",
            data: { "Qtd": $('.qtda').Value, "Id": Id.textContent }
        })
        alert("Materiais Adicionados!");
    }
    else {
        alert("Informe a quantidade do material!")
    }

})

Test in Firefox with firebug, which is easier to read the console result.log.

Browser other questions tagged

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