0

I'm loading data into a table using ajax that calls my controller function. When a new page is selected or a column is sorted, I reload the data by using ajax to that same original controller function. This is so that I don't load all of the items right away, only when needed. I want to make each row have an onclick javascript function where I can get the column information from that row that was clicked. Any ideas? The controller function just gets my data based on what result range the user wants to see and what sorted order.

My only javascript code is the following:

<script>
    $(function() {
        var oTable;
        oTable = $('#tblItemModel').DataTable({
            "serverSide": true,
            "paginate": true,
            "ajaxSource": "/Finance/ItemListAjax",
            "processing": true,
            "serverMethod": "GET",
            "displayLength": 50
        });
    })
</script>

My html is the following:

<table class="table table-striped at-table" id="tblItemModel">
      <thead>
            <tr>
                <th>
                    Id
                </th>
                <th>
                     @Html.DisplayNameFor(model => model.Name)
                </th>
                <th>
                   @Html.DisplayNameFor(model => model.ListPrice)
                </th>
                <th>
                      @Html.DisplayNameFor(model => model.DiscountPrice)
                </th>
          </tr>
     </thead>
     <tbody class="mousechange"></tbody>
</table>

1 Answer 1

3

I usually work in this way to get data when you click in a row...

in dataTable()

    $('#tblItemModel tbody').on('click', 'tr', function () {

       var pos = oTable.fnGetPosition(this);
       var row = oTable.fnGetData(pos);//row = It contains all the data in that row

    });

for DataTable()

    $('#tblItemModel tbody').on('click', 'tr', function () {

       var pos = oTable.row(this).index();
       var row = oTable.row(pos).data();//row = It contains all the data in that row

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

2 Comments

That will not work since oTable in the question is an instance of DataTable. It would work if oTable was an instance of dataTable instead. Replace oTable with $('#tblItemModel').dataTable() to correct this. Or use 1.10.x API instead.
Great! That did the trick. I was making some progress with "fnDrawCallback": function () { } in the initialization of the table, but yours is simpler.

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.