0

I've been looking over and over this one for a while and just can't see where the issue is. This should be a simple thing. What I'm doing is putting a link in a table header column to "Select All" and that would check all of the checkboxes. I've found code to do that but for some reason I can't get the click to even show a simple alert. When I click on the link nothing happens and there are no errors in the DevTools console either.

This is the basic code. I've copied and pasted the ID to make sure there wasn't an misspell but I'm thinking I'm overlooking something simple. I even wrote out the $(document).ready instead of using the $ short cut...grasping for anything.

$(document).ready(function () {

    //$("#checkAll").change(function () {
    //    $("input:checkbox").prop('checked', $(this).prop("checked"));
    //});

    $("#checkAll").click(function () {
        alert("clicked");
    });

});


<th class="col-md-1">
    <a href="#" id="checkAll">Select All</a>
</th>

Not sure if this has something to do with it but the table is in a MVC partial view that get's loaded by Ajax. Also, the JS code is in a separate file and not in the page. I know that the reference to that JS file is good because it also contains the Ajax code and that piece is working.

Any ideas on what I can try?

Caverman
  • 3,371
  • 9
  • 59
  • 115
  • You need to use [Event Delegation](https://learn.jquery.com/events/event-delegation/) for dynamically added elements –  Feb 16 '18 at 21:28
  • 1
    [Keep Calm and Call .on()](https://www.keepcalm-o-matic.co.uk/p/keep-calm-and-call-on-108/) – user9263373 Feb 16 '18 at 21:34
  • 1
    @VictorHerasmePerez - No (`#checkAll` does not exist initially in the DOM) - its `$(someElement).on('click', '#checkAll', function() {...` where `someElement` is the closest ancestor that exists in the initial page –  Feb 16 '18 at 21:41
  • Yep....still not working. Thanks Stephen, although I don't have it working yet I figure it might have something to do with it being inserted with Ajax so it would make sense that the #checkAll may not be in the DOM. I'm going to have to come back to this next week. I've had enough for today....it's Friday....and it's beerthirty! – Caverman Feb 16 '18 at 21:50
  • I'm back on this issue today. I've been doing a little searching but I'm not coming up with what looks to be an answer. One question would be that I might add the JS code in the partial view but I thought I saw through some of the research where this is not recommended. This question is marked as a duplicate but I can't find that duplicate question, probably doe to my not so good searching skills. If anyone knows of another article that would address this can you please post that one here. – Caverman Feb 20 '18 at 16:35

0 Answers0