1

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;
3
  • Not enough known. Sounds like your code runs before elements exist or you have other script errors. Provide a demo that replicates problem Commented May 21, 2016 at 15:31
  • I think you should put your js in $(document).ready(function(){/*Your code here*/}). Commented May 21, 2016 at 15:36
  • jsfiddle.net/nxjkzs0c/2 this is demo without css. Commented May 21, 2016 at 17:39

1 Answer 1

1

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/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.