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.
3
Answers
.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
insidetr
.Please Note: The attribute
id
must be unique indocument
.Try:
Demo:
You added rows dynamically so use
document
OR if you dont want to use class then use as
Ajax is Asynchronous And when you write This Code
that checkbox didn’t add to table Then you have to solution first
or you can use this solution