S.Gray
S.Gray

Reputation: 69

Event not working in JQuery when building table dynamically

I have an AJAX post that returns a data set. this part works completely fine.

However when building the table in the success area of the AJAX GET i create a Checkbox for each row.

When i then carry out an "On Click" Event of the checkbox it doesn't work.

Here is the AJAX/Table creation

function ListAppointments() {

$.ajax({
    type: "GET",
    url: "../Appointments",
    data: { 'id': id },
    contentType: "application/json; charset=UTF-8",
    dataType: "json",
    success: function (response) {
        if (response.length > 0) {
            $.each(response, function (i, item) {

                var apptDate, apptTime, arrivalTime = "";
                if (item.ApptDateTime != null) {
                    apptDate = moment(item.ApptDateTime).format('DD-MMM-YYYY');
                    apptTime = moment(item.ApptDateTime).format('HH:mm');
                }

                var row = '<tr class="grid__row--select"' + item.ID + '">' +
                    '<td><input id="check" name="check" id="chk" class="chkBoxOPA" type="checkbox" value="' + item.ID + '"/></td>' +
                    '<td style = "white-space:nowrap;">' +
                    '<div class="media-left">' +
                    '</div>' +
                    '<div class="media-body">' +
                    '<h3 class="list-group-item-heading">' + item.DisplayName + '</h3>' +
                    '<span class="list-group-item-text">' + item.DisplayDOB + '  (' + item.DisplayAge + ')</span>' +
                    '</div>' +
                    '</td>' +
                    '<td class="text-center" style="white-space:nowrap;">' +
                    '<span class="list-group-item-heading">' + apptDate + '</span>' +
                    '<span class="list-group-item-text">' + apptTime + '</span>' +
                    '</td>' +
                    '<td>' +
                    '<span class="grid__row--smaller-text">' + item.OutcomeDesc + '</span>' +
                    '</td>' +
                    '<td class="text-center" style="white-space:nowrap;">' +
                    '<span class="grid__row--smaller-text">' + arrivalTime + '</span>' +
                    '</td>' +
                    '</tr>';

                $('#appointments-body').append(row);
            });
        }
        else {
            console.log(JSON.stringify(response));
        }
    },
    error: function (response) {
        console.log(JSON.stringify(response));
    }
});

}

When i then try to do this

    $(".chkBoxOPA").on("change", ":checkbox", function () {
        alert('test');
    });

It doesnt seem to bind or work.

The ListAppointments function is run on a button click event.

Upvotes: 0

Views: 56

Answers (3)

Mamun
Mamun

Reputation: 68933

.chkBoxOPA and :checkbox refers to the same element but with your selector you are looking for :checkbox inside .chkBoxOPA and the selector fails to target the check box. You can find the element .chkBoxOPA inside tr.

Please Note: The attribute id must be unique in document.

Try:

$("tr").on("change", ".chkBoxOPA", function () {
    alert('test');
});

Demo:

var checkbox = `<td><input name="check" class="chkBoxOPA" type="checkbox" value="item1"/></td>`;
$('tbody tr').append(checkbox); //add check box dynamically
$("tr").on("change", ".chkBoxOPA", function () {
    alert('The index is: ' + $(".chkBoxOPA").index(this));
});
table, th, td {
  border: 1px solid black;
  border-collapse: collapse;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table style="width:100%">
  <thead>
    <tr>
      <th>Firstname</th>
      <th>Lastname</th>
      <th>Check</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Jill</td>
      <td>Smith</td>
    </tr>
    <tr>
      <td>Eve</td>
      <td>Jackson</td>
    </tr>
  </tbody>
</table>

Upvotes: 1

MBadrian
MBadrian

Reputation: 409

Ajax is Asynchronous And when you write This Code

$(".chkBoxOPA").on("change", ":checkbox", function () {
        alert('test');
    });

that checkbox didn't add to table Then you have to solution first

$.ajax({
    .....
    async:false,
    .....
})

or you can use this solution

......
$('#appointments-body').append(row);
$(".chkBoxOPA").on("change", ":checkbox", function () {
        alert('test');
    });
.......

Upvotes: 0

Devsi Odedra
Devsi Odedra

Reputation: 5322

You added rows dynamically so use document

$(document).on("change", ".chkBoxOPA", function () {
    alert('anything');
});

OR if you dont want to use class then use as

$(document).on("change", "input[type=checkbox]", function () {
        alert('anything');
    });

Upvotes: 2

Related Questions