Q:

Javascript function not triggering from Jquery Datatables row

I have a table that uses datatables and I want to trigger a function when I select a link on a row like this:
<script>
        var selected = Array();
        var form_data = {
            "Id": "@Model.ApplicationDetails.Id"
        };
        $(document).ready(function () {
            var table = $("#table").DataTable({
                "ajax": {
                    "url": "@Url.Action("GetApplicationRoles", @ViewContext.RouteData.Values["controller"].ToString())",
                    "type": "POST",
                    "data": form_data,
                    "datatype": "json"
                },
                "filter":false,
                "language": {
                    "search": "",
                    "searchPlaceholder": " Search"
                },
                "ordering": true,
                "lengthChange": false,
                "columns": [
                    {
                        "data": function (data, type, row, meta) {
                             var url = "@Url.Action("EditRole", @ViewContext.RouteData.Values["controller"].ToString())/" + data.Id;
                            return "<a href='#' class='select-item' data-id='"+data.Id+"'>" + data.RoleName + "</i></a>"
                        }, "name": "RoleName"
                    }
                ],
                "responsive": true,
                "processing":true,
                "serverSide": true,
            }).columns.adjust()
            .responsive.recalc();
            new $.fn.dataTable.FixedHeader(table);
        });

        $("#table tbody").on('click',".select-item",function (e) {
            e.preventDefault();
            alert("test");
            return false;
            //e.preventDefault();
            //console.log($(this).data("id"));
        });
    </script>

As you can see, when a user clicks on this row: 
<a href='#' class='select-item' data-id='"+data.Id+"'>" + data.RoleName + "</i></a>

The function at the bottom should trigger. However, right now the only thing that happens is that my url is appended by a hash#. I think I missed something but I can't seem to catch it.

A:

You're using a delegated event handler, which is correct. However one issue is because the primary selector needs to be an element that is present in the DOM when the page loads. The tbody element is also dynamically generated, so the event handler is not attached correctly.
To fix this, attach the event to the #table directly:
$('#table').on('click', '.select-item', function(e) {
  e.preventDefault();
  alert("test");
});

You also need to move that code block inside the document.ready event handler.

