Execute JavaScript function in the click event of a button inside a table

3

Hello, I have a table and in each row of this table I have a button, when I click that button I need to execute a function but I can not do that because I do not think I'm using the correct selectors. p>

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 that I want to run on 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!")
    }

})
    
asked by anonymous 28.08.2014 / 17:01

2 answers

8

The problem seems to me that you are trying to find the buttons to wait for the 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, since it is already on the page from the beginning, filtering to only the clicks that come from the 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!")
    }

})
    
28.08.2014 / 17:32
0

It seems to be all right. Did you do any debugging 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 console.log result.

    
28.08.2014 / 17:30