Deleted Rows appear back upon adding new row DataTables

南笙酒味 提交于 2019-12-11 12:21:44

问题


Hi i am a newbie to DataTables .... i have a data table in which i would like to add rows (one at a time) and have the capability of a multirow delete. I have managed to get the normal functionality working but the problem is that when i delete a row/rows and then try to add a new row the deleted rows appear back in the same positions as selected rows .... below is the code i am using to initialize the DataTable and the functionality to add and delete rows in my DataTable.... Any help would be appreciated ...

            $(document).ready(function (){
            var counter = 1
            $('#addRow').on( 'click', function (a,b,c,d,e,f) {

            a = "test"

            t.row.add( [
                 counter +a,
                 counter +'test',
                 counter +'test',
                 counter +'test',
                 counter +'test',
                 counter +'test'
             ] ).draw(false);
               counter ++;
             } );


            $('#example tbody').on( 'click', 'tr', function (e) {
                if ( $(this).hasClass('selected') ) {
                    $(this).removeClass('selected');
                    $(this).css('background-color', '')
                }
                else {
                    t.$('tr.selected');//.removeClass('selected');
                    $(this).addClass('selected');
                    $(this).css('background-color', 'blue');
                }
            } );


            $('#removeRow').click( function () {
                var anSelected = fnGetSelected( t );
                $(anSelected).remove();
        } );    

             var t = $('#example').DataTable({
            'fnCreatedRow': function (nRow, aData, iDataIndex) {
            $(nRow).attr('id', 'my' + iDataIndex); 
            },
            "aoColumnDefs": [ {
              "aTargets": [0,1,2,3,4,5],
              "fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
                    var idx = t.cell( nTd ).index().column;
                    var title = t.column( idx ).header();
                    $(nTd).attr("id",$(title).html() +"_"+ iRow)
                }
            } ]
    });



});

          function fnGetSelected( oTableLocal )
         {
          return oTableLocal.$('tr.selected');
         }

The above code is just to test functionality with a few things not required....

**** Update on post **** The table html is written in a template which i am calling inside a form ... The parent gsp file with form code is below .....

Main gsp file

    <g:form action="saveTravelDetails" id="createRequest" name="createRequest" autocomplete="off">                       
<g:render template="newTravelRequest" />
<div class="row">
    <div class="col-md-12">
        <div class="form-group" style="text-align: center;">
            <input id="circuit_save" class="btn btn-primary circuit_validate" tabindex="700" class="button_text" type="submit" name="circuit_save" value="Save" />
            <input id="circuit_cancel" class="btn btn-default" class="button_text" type="button" name="circuit_cancel" value="Cancel" />
            <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#detailsModal">Add new row</button>
            <button type="button" class="btn btn-primary" id="removeRow">Remove Selected Row</button>
        </div>
    </div>
</div>
</g:form>

The template html code is below

<div class="row">
    <div class="col-md-12">
        <div class="panel panel-default">
            <div class="panel-heading">
                <i class="fa fa-user"></i> Travel Details
                <div class="panel-tools">
                    <a href="#" class="btn btn-xs btn-link panel-collapse collapses">
                    </a>
                </div>
            </div>
            <div class="panel-body">
            <table cellpadding="0" cellspacing="0" border="0" class="display" id="example">
              <thead class="alignCenter">
                 <tr>
          <th class="headerclass">Departure Date</th>
          <th class="headerclass">Return Date</th>
          <th class="headerclass">Departure Destination</th>
          <th class="headerclass">Arrival Destination</th>
          <th class="headerclass">Choose Mode Of Transport</th>   
          <th class="headerclass">Cost of Travel</th>        
                 </tr>
              </thead>
              <tbody></tbody>
              <tfoot  class="alignCenter headerclass">
                 <tr>
          <th class="headerclass">Departure Date</th>
          <th class="headerclass">Return Date</th>
          <th class="headerclass">Departure Destination</th>
          <th class="headerclass">Arrival Destination</th>
          <th class="headerclass">Choose Mode Of Transport</th>   
          <th class="headerclass">Cost of Travel</th>       
                 </tr>
              </tfoot>
              </table>

            </div>
        </div>
    </div>
</div>

The updated javascript code in the main file which initializes the DataTable is given below ... this also has the function definition to Add and Delete rows

$(document).ready(function (){


        var counter = 1
     $('#addRow').on( 'click', function () {

            t.row.add( [

                $('#departureDate_1').val(),
                $('#returnDate_1').val(),
                $('#startDestination').val(),
                $('#endDestination').val(),
                $('#travelMode').val(),
                $('#travelFare').val(),

            ] ).draw(false);
            counter ++;

            $('#detailsModal').modal('hide');
        } );


                $('#example tbody').on( 'click', 'tr', function (e) {
                    if ( $(this).hasClass('selected') ) {
                        $(this).removeClass('selected');
                        $(this).css('background-color', '')
                    }
                    else {
                        t.$('tr.selected');//.removeClass('selected');
                        $(this).addClass('selected');
                        $(this).css('background-color', 'blue');
                    }
                } );


            $('#removeRow').click( function () {
                    var anSelected = fnGetSelected( t );
                    $(anSelected).remove();
            } );    

        var t = $('#example').DataTable({
                'fnCreatedRow': function (nRow, aData, iDataIndex) {
                $(nRow).attr('id', 'my' + iDataIndex);
                $(nRow).attr('name', 'my' + iDataIndex); // or whatever you choose to set as the id
                },
                "aoColumnDefs": [ {
                  "aTargets": [0,1,2,3,4,5],
                  "fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
                        var idx = t.cell( nTd ).index().column;
                        var title = t.column( idx ).header();
                        $(nTd).attr("name",$(title).html() +"_"+ iRow)
                        $(nTd).attr("id",$(title).html() +"_"+ iRow)
                    }
                } ]
        });

        $('#departureDate').on('change',function (){
            $('.bootstrap-datetimepicker-widget').css('display','none');
        });

        $('#returnDate').on('change',function (){
            $('.bootstrap-datetimepicker-widget').css('display','none');
        });


        $('#departureDate').datetimepicker({
            format: 'YYYY-MM-DD',
            pick12HourFormat: false,
            autoclose: true
        });

        $('#returnDate').datetimepicker({
            format: 'YYYY-MM-DD',
            pick12HourFormat: false,
            autoclose: true
        });



    });

function fnGetSelected( oTableLocal )
{
    return oTableLocal.$('tr.selected');
}

Thanks in advance


回答1:


Try

 $(anSelected).remove().draw(false);

As it is now you only redraw the table after adding a new row. As stated by the draw() docs:

A draw is not performed automatically by most DataTables API actions to allow grouping of actions (for example adding multiple rows is more efficient if you group them.

A good option would be to draw after you bulk-removed the rows.




回答2:


thanks for reading my question and taking the time to answer it i found the solution ... Below is the code which can be used in other scenarios also ....

$('#removeRow').click(function() {
    var anSelected = fnGetSelected(t);
    alert(anSelected);
    t.row(anSelected).remove().draw(false);
});

function fnGetSelected(oTableLocal) {
    return oTableLocal.$('tr.selected');
}


来源:https://stackoverflow.com/questions/35813626/deleted-rows-appear-back-upon-adding-new-row-datatables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!