1

enter image description here

enter image description here

enter image description here

Code

HTML

    <ul class="nav nav-pills mytab">
       <li class="nav-item">
          <a class="nav-link active" bankid="1" href="#test1" data-toggle="tab"><i class="fa fa-university"></i> test1</a>
      </li>
                                                                                                                    <li class="nav-item">
         <a class="nav-link" bankid="2" href="#test2" data-toggle="tab"><i class="fa fa-university"></i> test2</a>
    </li>
    </ul>

<table id="table_{{$bvl['id']}}" class="table table-bordered table-striped" cellpadding="0px" width="auto" cellspacing="0px">
                                        <thead id="headD">
                                            <tr></tr>
                                            <tr></tr>
                                        </thead>
                                        <tbody id="dataD" runat="server"></tbody>
                                        <tfoot>
                                            <tr></tr>
                                        </tfoot>
                                    </table>

Javascript

 $('.mytab a').on('click', function (e) {
                var bankid = $(this).attr("bankid");
                getTableMeta(bankid);
            })

//get column data
function getTableMeta(bankid) {
    table          = "";
    ColumnData     = "";
    EditRowData    = [];
    mdataArray     = [];
    isEditAllState = false;
    defaultcol     = "";

    $('#table_'+bankid+' thead tr:first-child th').remove();
    $('#table_'+bankid+' thead tr:nth-child(2) th').remove();
    $('#table_'+bankid+' thead tr:first-child td').remove();
    $('#table_'+bankid+' thead tr:nth-child(2) td').remove();

    $.ajax({
        type: 'POST',
        url: "{{route('getcolumn')}}",
        data: {
            "_token": "{{ csrf_token() }}",
        },
        dataType: 'json',
        success: function (data) {

            ColumnData   = data.Column;
            var inputype = "";
            $.each(data.Column, function (index, element) {
                //title
                $('#table_'+bankid+' thead tr:first-child').append($('<th>', {
                    text: element.Name
                }));

                //insert
                if (data.Insertable == true) {
                    if (element.Editable == true) {
          
                        if(element.Name == 'in' || element.Name == 'out'){
                            inputype = 'number';
                        }else if(element.Name == 'time'){
                            inputype = 'time';
                        }else{
                            inputype = 'text';
                        }

                        $('#table_'+bankid+' thead tr:nth-child(2)').append($('<th class="'+element.Name+'"><input class="'+element.Name+'Add_'+bankid+'" style="width: 99% " type="'+inputype+'" /></th>'));
                    }else{
                        $('#table_'+bankid+' thead tr:nth-child(2)').append($('<th></th>'));
                    }
                }

                mdataArray.push({ mData: element.Name, class: element.Name });
            });

            if (data.Deletable == true) {
                $('#table_'+bankid+' thead tr:first-child').append($('<th>', {
                    text: 'Action'
                }));
                mdataArray.push({ defaultContent: '<span class="deleteBtn"><i class="fa fa-trash-o fa-lg" aria-hidden="true"></i></span>', class: 'DeleteRow' });

            }
            if (data.Insertable == true) {
                $('#table_'+bankid+' thead tr:nth-child(2)').append($('<td><span class="insertBtn"><i class="fa fa-plus fa-lg" aria-hidden="true"></i></span></td>'
                ));
            }
            defaultcol = data.Column[0].Name;
            //once table headers and table data property set, initialize DT
            initializeDataTable(bankid);

        }
    });
}

//get row data
function initializeDataTable(bankid) {

    table = $('#table_'+bankid).DataTable({
        "ajax": {
            url: "{{route('getcolumndata')}}",
            "type": "POST",
             data: function (data) { 

                editIndexTable = -1;
                var colname;
                var sort = data.order[0].column;
                if (!data['columns'][sort]['data'] == '')
                    colname = data['columns'][sort]['data'] + ' ' + data.order[0].dir;
                //in case no sorted col is there, sort by first col
                else colname = defaultcol + " asc";
                var colarr = [];
                var colfilter, col;
                var arr = {
                    'draw': data.draw, 
                    'length': data.length,
                    'sort': colname, 
                    'start': data.start, 
                    'search': data.search.value,
                    'bankid': bankid,
                    '_token': "{{ csrf_token() }}"
                };
                //add each column as formdata key/value for filtering
                data['columns'].forEach(function (items, index) {
                    col = data['columns'][index]['data'];
                    colfilter = data['columns'][index]['search']['value'];
                    arr[col] = colfilter;
                });
                
                return arr;
            }
           
        },
        "bSortCellsTop": true,
        "orderable": false,
        "destroy": true,
        "lengthMenu": [10, 50, 100],
        "iDisplayLength": 100,
        "searching": true,
        serverSide: true, 
        "processing": true,
        "columnDefs": [{ 'targets': 1, 'visible': false }],
        aoColumns: mdataArray
    });

    //for insert button
    $("#table_"+bankid+" thead").on('click', 'tr td span.insertBtn', function (e) {
        console.log("a"); //here will console duplicate data depend on the tab user click
        insertRowData(this.parentNode.parentNode, bankid);
    });

}

Question: I have created a tab using bootstrap nav tab. For each tab it will have bankID, depending on user click and will pass the bankID and render the datatable. Above code is work fine, but it will be facing one problem which is duplicate called. Does it mean that, if user random play and click around with the tab 1(test1) or tab 2(test2), when they try to insert the data it will have the duplicate enter issue. I tried to console.log inside the onClick function, it will have multiple console. It will depend on how many time that user click the tab. For example, first time when they click the tab 2(test2) and then click tab 1(test1) then click tab 2(test2) again, it will have 2 duplicate enter. Anyone can help on this? I get stuck at this issue long time :(

2
  • can you please tell your javascript code is render through ajax or on page refresh? Commented Dec 29, 2020 at 6:19
  • @SandeepK. through ajax Commented Dec 29, 2020 at 6:19

2 Answers 2

1

can you please use this code before your click function.

$('.mytab a').off('click');

for Add row click

$("#table_"+bankid+" thead tr td span.insertBtn").off('click');

$("#table_"+bankid+" thead").on('click', 'tr td span.insertBtn', function (e) {
    console.log("a"); //here will console duplicate data depend on the tab user click
    insertRowData(this.parentNode.parentNode, bankid);
});
Sign up to request clarification or add additional context in comments.

6 Comments

cannot, still the same.
you have set all click function to off where you have use. If your jquery or javascript code is loaded by ajax.
can provide some example ya?
like $('.mytab a').off('click');
by using this function previous clicks is cleared.
|
0

I think it's because you just remove "thead row", you must remove tbody rows or create another table for every tabs.

Comments

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.