Ardahan Kisbet Ardahan Kisbet - 6 months ago 23
Javascript Question

How to find checkbox in table using JQuery?

I have a table which has only checkbox in first column of each rows. I want to find which checkbox clicked with Jquery (change event). I try this but nothing show up:

$('#table tbody tr td input[type=checkbox]').change(function () {
if (this.checked) {
alert("true");//for testing purposes
}
alert("false");
});


How to I get clicked element?

<table id="table" class="table table-hover table-striped table-bordered">
<thead>
<tr>
<th class="col-lg-1">Sıra No.</th>
<th class="col-lg-3">İsim/No</th>
<th class="col-lg-6">Koordinat Bilgisi</th>
<th class="col-lg-2">Mahalle/Kapı</th>
</tr>
</thead>
<tbody id="tableBody">
</tbody>
</table>


Edit: My table body is empty in the beginning. I am filling table body after I click a button. And each rows first column has a input element created with plain javascipt.

var indexCheckbox = document.createElement('input');
indexCheckbox.type = "checkbox";
indexCheckbox.name = "indexCheckbox";
indexCheckbox.value = i;
indexCheckbox.id = "indexCheckbox_" + i;

Answer

An event-delegation approach attaches an event handler to only one element, the checkbox, and the event only needs to bubble up one level (from the clicked checkbox to #tableBody):

$('#tableBody').on("change", "input[type=checkbox]", function () {
    if (this.checked) {
       alert("true");//for testing purposes
    }else{
       alert("false");
    }
});

Result: https://jsfiddle.net/pLrk1vrf/