jQuery Datatable dynamic edit button attached to e

2020-07-11 05:34发布

问题:

totally new to jquery and datatable. I would like to add an edit button that call forth a colorbox div that displays all the editable field. can anyone point me in the right direction on how this can be achieved?

I was able to add a sClass to each field and use fnDrawCallback callback to call colorbox from field. But this is kind of messy and I rather just have a button at the end of each row for edit purpose. thanks very much for any pointers.

回答1:

You can add stuff by fnCreatedCell callback in a column definition in aoColumnDefs the following adds a button to the first row, with a onclick event handler that redirects to the value in the first column (this is somthing you might whant to change.

"aoColumnDefs" : [ 
                    {
                        "aTargets": [0],
                        "fnCreatedCell" : function(nTd, sData, oData, iRow, iCol){
                            var b = $('<button style="margin: 0">edit</button>');
                            b.button();
                            b.on('click',function(){
                                document.location.href = oData[0];
                                return false;
                            });
                            $(nTd).empty();
                            $(nTd).prepend(b);
                        }
                    },


回答2:

I would reccomend using the excellent DataTables Editable plugin. The plugin makes it very easy to edit fields directly in the table.

If you really want to have a button on each row, you can either add it when you generate the table serverside, or add it using jQuery. Then you would need to bind an action to the buttons.

Let say you want to inject the buttons, the code becomes something like this:

$('#form-id').delegate('.edit-button', 'click', function() {
   // action
}).find('.classname-of-field-for-button').html('<button class="edit-button">');