-2

On change of a dropdown I add dynamically a row to a table. in the last cell of the row I'm adding I have a button with class".ups".

The problem is that it seems maybe that this dynamically added row is not added to the DOm and my jquery selector .ups doesn't work

  $(document).ready(function () {

    $("#drdCriterias").change(function () {


        var table = document.getElementById("tableCriterias");
            var row = table.insertRow(-1);
            var cell1 = row.insertCell(0);
            var cell2 = row.insertCell(1);
            var cell3 = row.insertCell(2);

            cell1.innerHTML = $('#drdCriterias').val();
            cell2.innerHTML = $('#drdCriterias :selected').text();
            cell3.innerHTML = '<button type="button" class="ups"><span class="glyphicon glyphicon-circle-arrow-up"></span></button>';

    });

    $("tr .ups").click(function () {
        alert("Hi"); //nothing happens

});
ozil
  • 6,001
  • 8
  • 28
  • 50
Tania Marinova
  • 1,852
  • 8
  • 35
  • 63

2 Answers2

1

Use event delegation:

$("body").on('click','tr .ups',function () {
    alert("Hi"); 
});
Milind Anantwar
  • 77,788
  • 22
  • 86
  • 114
0

Have you tried wrapping the click event with a function and calling it everytime you add a relevant button.

$(document).ready(function () {

$("#drdCriterias").change(function () {


    var table = document.getElementById("tableCriterias");
        var row = table.insertRow(-1);
        var cell1 = row.insertCell(0);
        var cell2 = row.insertCell(1);
        var cell3 = row.insertCell(2);

        cell1.innerHTML = $('#drdCriterias').val();
        cell2.innerHTML = $('#drdCriterias :selected').text();
        cell3.innerHTML = '<button type="button" class="ups"><span class="glyphicon glyphicon-circle-arrow-up"></span></button>';
    upsClick();

});

function upsClick() {
   $("tr .ups").click(function () {
       alert("Hi"); //nothing happens
   });
}
Mō Iđɍɨɇƶ
  • 311
  • 1
  • 8