简体   繁体   中英

Dynamically add id to datatable row based on AJAX response

I have seen posts on giving arbituary ids to datatable rows using row callback here . I want to give rows specific ids based on my AJAX response dataToUse ; each row will have a unique id given as one field of a JSON object. Here's the structure of my datatable:

table = $('#_table').dataTable({
                ajax: function (data, callback, settings) {
                    $.ajax({
                             type: "post",
                             url: '/test/getvalues',
                             dataType: "json",
                             success: function (result) {
                                var dataToUse = {};
                                dataToUse.data = result.map.count;
                                callback(dataToUse);
                             }
                           });
                  }
        })

}

Do you just want to perform some operation on particular rows based on the information you get from dataToUse? To begin, I'll describe the behavior that is happening in the example you provide. The code reads:

if ( data[5].replace(/[\$,]/g, '') * 1 > 150000 ) {
    $('td', row).eq(5).addClass('highlight');
}

Which is checking to see if the 6th item in data, the salary, is greater than 150,000, and if it is, selecting that item using a CSS selector through jQuery and then is adding a class to it.

Based on your question, you want to perform a similar table-modifying behavior based on some data provided by result to dataToUse. In that case, result will need to provide some sort of information that allows you to construct an appropriate jQuery selector, $(someSelector) to choose the rows you want to modify, and then you can modify them as needed. You can perform all this in your success function.

I would suggest updating their classes rather than ids if you want to add some specific styling or behavior to them. Updating the id tends to be bad practice.

this post , whose answer has been pasted here, gives the answer,

    'fnCreatedRow': function (nRow, aData, iDataIndex) {
        $(nRow).attr('id', 'my' + iDataIndex); // or whatever you choose to set as the id
    },

aData somehow is the AJAX data that I received. This is like magic to me but it worked!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM