jquery - Datatables Column Misalignment and Duplicate sort arrow issue -


each time display table additional sort arrow added <th>.

here image of issue: issue 1

i having issue columns not aligning correctly. happens sometimes, other times works fine. if click/sort table, columns snap align correctly. here image link of issue: issue 2

i have reinitialize table each time different data, have this:

$('#car').empty(); table2.clear().draw(); 

if know of better way destroy , recreate please let me know. think may causing column alignment issue.

here javascript code.

function format(notes) {     var object = notes.data;     var out = '<table id="display" style="font-size: 12px; min-width: 90%; margin-left: 90px; margin-bottom:10px; border-bottom:1px solid lightgray;">';     out += '<thead><tr><th class="ui-state-default">answer</th><th  class="ui-state-default"># of answers</th>';     out += '<th class="ui-state-default">percent</th></tr></thead><tbody>';     (var in object) {          out += '<tr><td>' + object[i].answer + '</td><td>' + object[i].numberofanswers + '</td><td>' + object[i].percent + '</td></tr>'     }      out += '</tbody></table>';     return out; }  $('#pacingmodal').on('shown.bs.modal', function (e) {     var cat = $("#pacingmodal").attr('category');     var status = $("#pacingmodal").attr('status');     var taskid = $("#pacingmodal").attr('taskid');      //fill category details table     $.ajax({          type: "post",         cache: false,         datatype: 'text',         url: '/rmsicorp/clientsite/reset/categorystatus/detail/catstatusdetaildata.php',         data: { category: cat, statustype: status, taskid: taskid },         beforesend: function () {             $('#loading').show();             $('#selectcontainer2').empty();         },         success: function (data) {             $("#cat2").html(data);             $('#loading').hide();         },         complete: function (data) {              var table = $("#cat2").find("#tabl").datatable({                 "scrolly": "400px",                 "scrollcollapse": true,                 "paging": false,                 "bautowidth": false,                 "jqueryui": true,                 "order": [[5, "asc"]],                 "tabletools": {                     "sswfpath": "/swf/copy_csv_xls_pdf.swf",                     "abuttons": [                         {                             "sextends": "xls",                             "sbuttontext": "excel hey!",                             "sfilename": "*.xls"                         },                     ]                 }             });          },         error: function () {             //todo - add auto email error             alert("error retriving data server! please check soon.");             //close modal if error             $("#pacingmodal").modal('hide');         }     });          var taskid = $('#pacingmodal').attr('taskid');     //var questionid = table2.cell('.shown', 0).data();     var table2 = $('#car').datatable({         destroy: true,         "ajax": {             "url": "/rmsicorp/clientsite/pacingmodal/surveyajax.php?taskid=" + taskid,             "type": "get"         },         "scrolly": "400px",         "paging": false,         "bautowidth": true,         "columns": [             {                 "classname": 'details-control',                 "orderable": false,                 "data": null,                 "defaultcontent": ''             },             {                 "data": "id",                 "type": "hidden"             },              { "data": "question" },         ],      });       var detailsrows = [];     $('#car tbody').on('click', 'td.details-control', function () {         var taskid = $('#pacingmodal').attr('taskid');         var tr = $(this).closest('tr');         var row = table2.row(tr);         var cell = row.data();         var rowid = cell.id;         var rid = $.inarray(tr.attr('id'), detailsrows);         $.ajax({             type: 'post',             url: '/rmsicorp/clientsite/pacingmodal/surveyajax2.php',             data: { taskid: taskid, questionid: rowid },             datatype: 'json',             success: function (result) {                 if (row.child.isshown()) {                     row.child.hide();                     tr.removeclass('shown');                     detailsrows.splice(rid, 1);                 }                 else {                     // console.log(result);                     row.child(format(result)).show();                     tr.addclass('shown');                      if (rid === -1) {                         detailsrows.push(tr.attr('id'));                     }                  }             }         });     });      $("#pacingmodal").on('hide.bs.modal', function () {         //empty html content out of div user not see last search before new 1 loads when click on different option         $('#cat2').empty();         $('#slidercontainer2').empty();         $('#car').empty();         table2.clear().draw();      });  }); 

and here html. both datatables inside bootstrap tabs inside bootstrap modal.

<div id="pacingmodal" class="modal fade" role="dialog">     <div class="modal-dialog modal-xl">         <!-- modal content-->         <div class="modal-content">             <div class="modal-header">                 <button type="button" class="close" data-dismiss="modal">&times;</button>                 <h4 id="modaltitle" class="modal-title">modal</h4>             </div>             <div class="modal-body">                 <div role="tabpanel">                     <!-- nav tabs -->                     <ul class="nav nav-tabs" role="tablist" id="modaltabs">                         <li role="presentation"><a href="#home" aria-controls="home" role="tab" data-toggle="tab">category details</a></li>                         <li role="presentation"><a href="#pacingmodalsurvey" aria-controls="survey" role="tab" data-toggle="tab">survey</a></li>                         <li role="presentation"><a href="#pacingmodalphotos" aria-controls="photos" role="tab" data-toggle="tab">photos</a></li>                     </ul>                     <!-- tab panes -->                     <div class="tab-content">                         <div role="tabpanel" class="tab-pane active" id="home">                             <p id="cat"></p>                             <div id="tablcontainer">                                 <div id="cat2"></div>                             </div>                         </div>                         <div role="tabpanel" class="tab-pane" id="pacingmodalsurvey">                             <p id="surveyp">                             </p>                             <div id="surveydiv">                                 <table id="car" class="display" cellspacing="0" width="100%" style="font-size: 12px;">                                     <thead>                                         <tr>                                             <th class="details-control" style="max-width: 80px;">expand</th>                                             <th>id</th>                                             <th>question</th>                                             <!-- <th>numberofanswers</th>                                             <th>answer</th>                                             <th>percent</th>-->                                         </tr>                                     </thead>                                     <tbody>                                     </tbody>                                      <tfoot>                                         <tr>                                             <th></th>                                             <th>id</th>                                             <th>question</th>                                             <!--   <th>numberofanswers</th>                                             <th>answer</th>                                             <th>percent</th>-->                                         </tr>                                     </tfoot>                                 </table>                             </div>                                <style>                                 td.details-control {                                     background: url('/rmsicorp/clientsite/images/details_open.png') no-repeat center center;                                     cursor: pointer;                                 }                                  tr.shown td.details-control {                                     background: url('/rmsicorp/clientsite/images/details_close.png') no-repeat center center;                                     cursor: pointer;                                 }                             </style>                          </div>                         <div role="tabpanel" class="tab-pane" id="pacingmodalphotos">                               <div class="container">                                    <div class="row" id="fullclass">                                     <div class="col-lg-12" style="padding-left: 0px !important; margin-bottom: 10px;">                                          <h5 style="vertical-align: middle; text-align: center; color: black; font-size: 16px; font-weight: bold; text-transform: uppercase;">photos</h5>                                         <div id="slidercontainer2">                                         </div>                                         <div id="selectcontainer2">                                             <h5>please search photos.</h5>                                         </div>                                         <div id="loadingcontainer2" style="vertical-align: central; text-align: center;">                                             <img src="/images/loading.gif" /><br />                                              <span class="load">loading...</span>                                         </div>                                     </div>                                 </div>                                </div>                         </div>                     </div>                      <p id="loading" style="text-align: center; vertical-align: central;">                         <img src="/images/loading.gif" />                         <br />                         <span>loading.</span>                     </p>                 </div>                 <div class="modal-footer">                     <button type="button" class="btn btn-primary" data-dismiss="modal">close</button>                 </div>             </div>         </div>     </div> </div> 

solution

there many problems code:

  1. columns misaligned because table initialized while being hidden. need readjust column widths using columns.adjust() once required tab , table becomes visible:

    $('a[data-toggle="tab"]').on('shown.bs.tab', function(e){    $($.fn.datatable.tables(true)).datatable()       .columns.adjust(); }); 
  2. you're trying hide column "id" incorrectly, besides hidden column causing issues while destroying table. have eliminated id column completely.

  3. table should cleared , destroyed using $(selector).datatable().clear().destroy().

  4. you're adding other event handlers inside event handler $('#pacingmodal').on('shown.bs.modal', function(){}); leads unnecessary multiple calls other event handlers.

there other minor issues not mentioned here.

see example below corrected code.

function format(notes) {    var object = notes.data;    var out = '<table class="display" style="font-size: 12px; min-width: 90%; margin-left: 90px; margin-bottom:10px; border-bottom:1px solid lightgray;">';    out += '<thead><tr><th class="ui-state-default">answer</th><th  class="ui-state-default"># of answers</th>';    out += '<th class="ui-state-default">percent</th></tr></thead><tbody>';    (var in object) {        out += '<tr><td>' + object[i].answer + '</td><td>' + object[i].numberofanswers + '</td><td>' + object[i].percent + '</td></tr>'    }      out += '</tbody></table>';    return out;  }    $(document).ready(function() {    // ajax emulation demonstration    $.mockjax({      url: '/rmsicorp/clientsite/pacingmodal/surveyajax2.php',      responsetime: 200,      responsetext: {        "data": [{          "answer": 1,          "numberofanswers": 2,          "percent": 3        }, {          "answer": 1,          "numberofanswers": 2,          "percent": 3        }, {          "answer": 1,          "numberofanswers": 2,          "percent": 3        }]      }    });      // ajax emulation demonstration    $.mockjax({      url: '/rmsicorp/clientsite/pacingmodal/surveyajax.php',      responsetime: 200,      responsetext: {        "data": [{          "id": 1,          "question": "question"        }, {          "id": 2,          "question": "question"        }, {          "id": 3,          "question": "question"        }]      }    });            // ajax emulation demonstration    $.mockjax({      url: '/rmsicorp/clientsite/reset/categorystatus/detail/catstatusdetaildata.php',      responsetime: 200,      responsetext: '<p class="text-center">no data</p>'    });      $('#btn-show').on('click', function() {      var box = $('#pacingmodal').modal();    });      $('#pacingmodal').on('shown.bs.modal', function(e) {      var cat = $("#pacingmodal").attr('category');      var status = $("#pacingmodal").attr('status');      var taskid = $("#pacingmodal").attr('taskid');        //fill category details table      $.ajax({          type: "post",        cache: false,        datatype: 'text',        url: '/rmsicorp/clientsite/reset/categorystatus/detail/catstatusdetaildata.php',        data: {          category: cat,          statustype: status,          taskid: taskid        },        beforesend: function() {          $('#loading').show();          $('#selectcontainer2').empty();        },        success: function(data) {          $("#cat2").html(data);          $('#loading').hide();        },        complete: function(data) {            var table = $("#cat2").find("#tabl").datatable({            "scrolly": "400px",            "scrollcollapse": true,            "paging": false,            "bautowidth": false,            "jqueryui": true,            "order": [              [5, "asc"]            ],            "tabletools": {              "sswfpath": "/swf/copy_csv_xls_pdf.swf",              "abuttons": [{                "sextends": "xls",                "sbuttontext": "excel hey!",                "sfilename": "*.xls"              }, ]            }          });          },        error: function() {          //todo - add auto email error          alert("error retriving data server! please check soon.");          //close modal if error          $("#pacingmodal").modal('hide');        }      });          var taskid = $('#pacingmodal').attr('taskid');      //var questionid = table2.cell('.shown', 0).data();      var table2 = $('#car').datatable({        destroy: true,        "ajax": {          "url": "/rmsicorp/clientsite/pacingmodal/surveyajax.php",          "type": "get"        },        "scrolly": "400px",        "scrollcollapse": true,        "paging": false,        "bautowidth": true,        "columns": [{          "classname": 'details-control',          "orderable": false,          "data": null,          "defaultcontent": ''        }, {          "data": "question"        }]        });          var detailsrows = [];      $('#car tbody').on('click', 'td.details-control', function() {        var taskid = $('#pacingmodal').attr('taskid');        var tr = $(this).closest('tr');        var row = table2.row(tr);        var cell = row.data();        var rowid = cell.id;        var rid = $.inarray(tr.attr('id'), detailsrows);        $.ajax({          type: 'post',          url: '/rmsicorp/clientsite/pacingmodal/surveyajax2.php',          data: {            taskid: taskid,            questionid: rowid          },          datatype: 'json',          success: function(result) {            if (row.child.isshown()) {              row.child.hide();              tr.removeclass('shown');              detailsrows.splice(rid, 1);            } else {              // console.log(result);              row.child(format(result)).show();              tr.addclass('shown');                if (rid === -1) {                detailsrows.push(tr.attr('id'));              }              }          }        });      });    });      $("#pacingmodal").on('hidden.bs.modal', function() {      //empty html content out of div user not see last search before new 1 loads when click on different option      $('#cat2').empty();      $('#slidercontainer2').empty();      $('#car').datatable().clear().destroy();    });      $('#modaltabs a[data-toggle="tab"]').on('shown.bs.tab', function(e) {      if ($(e.target).attr('href') === '#pacingmodalsurvey') {        $('#car').datatable().columns.adjust();      }    });    });
<!doctype html>  <html>    <head>    <meta charset="iso-8859-1">      <link href="//cdn.datatables.net/1.10.7/css/jquery.datatables.min.css" rel="stylesheet" />    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>    <script src="//cdn.datatables.net/1.10.7/js/jquery.datatables.js"></script>    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>    <script src="http://vitalets.github.com/x-editable/assets/mockjax/jquery.mockjax.js"></script>    </head>    <body>    <div class="container text-center">      <button id="btn-show" class="btn btn-primary">show dialog</button>    </div>      <div id="pacingmodal" class="modal fade" role="dialog">      <div class="modal-dialog modal-xl">        <!-- modal content-->        <div class="modal-content">          <div class="modal-header">            <button type="button" class="close" data-dismiss="modal">&times;</button>            <h4 id="modaltitle" class="modal-title">modal</h4>          </div>          <div class="modal-body">            <div role="tabpanel">              <!-- nav tabs -->              <ul class="nav nav-tabs" role="tablist" id="modaltabs">                <li role="presentation"><a href="#home" aria-controls="home" role="tab" data-toggle="tab">category details</a>                </li>                <li role="presentation"><a href="#pacingmodalsurvey" aria-controls="survey" role="tab" data-toggle="tab">survey</a>                </li>                <li role="presentation"><a href="#pacingmodalphotos" aria-controls="photos" role="tab" data-toggle="tab">photos</a>                </li>              </ul>              <!-- tab panes -->              <div class="tab-content">                <div role="tabpanel" class="tab-pane active" id="home">                  <p id="cat"></p>                  <div id="tablcontainer">                    <div id="cat2"></div>                  </div>                </div>                <div role="tabpanel" class="tab-pane" id="pacingmodalsurvey">                  <p id="surveyp">                  </p>                  <div id="surveydiv">                    <table id="car" class="display" cellspacing="0" width="100%" style="font-size: 12px;">                      <thead>                        <tr>                          <th class="details-control" style="max-width: 80px;">expand</th>                          <th>question</th>                        </tr>                      </thead>                      <tbody>                      </tbody>                        <tfoot>                        <tr>                          <th></th>                          <th>question</th>                        </tr>                      </tfoot>                    </table>                  </div>                        <style>                    td.details-control {                      background: url(data:image/png;base64,ivborw0kggoaaaansuheugaaabqaaaaucayaaacnir0naaacjeleqvr4aa2v30uturjhnvbugglcaxvtjjvlmdhqm7+1jevjikaggmgsqikjl0v0e13uvf0hqzmblcvlpqa55tqv0yomzihy6js0ydh11x17vuo8sq5zgl/48dznpd/g63nomsmbkounwhyhtugn9nuey8z5p0wqovxykrwqlmjhhyv7kpaqck2rndskbbpmdrv9osfjcqadww/rahsr0ocey8xhrqox/a3zzmghko9wob7ouj6pbgkmocxlzcqmddykgzmzmswjo6pviyosrudwxgj50iwtb4+hxlen5savvjh4jvbcgbrzwso121upk3eaaukuz+d7yctp+wnc/nwl1d4qhbvidmjzv/npbkjzgiiv19vfwmgrcvdsvkupqeky/056vmf1j9dqovibko9aa/ixdbnycrqgwsbc1jq2ntrzq/vkshhm8kvdepvn9qjsobrl/auohyij+upccxjttmfcdyohjt2yyyolptcacoumggwdbkvrbxgk+2y0gg2gisuvnmjcy/bvujqm/ebixxqpgbutibise12hqlc+clwfskrcizh6wxpqs7ozetwn6xena/tryemywuk0ipgstotgru3fcvbzouwg6ponpqy0bhuggpdxeujiw7jkcfux3tjjp9k4fbkzn4pty+042jgzznmcgdj35c7tmcu++tjmje63opsuulej62gcfxuo+59kr8rjnloy0wfagtyay/phypv9fhdey7++4nz/bws17upwy0es2avwp3voyotncchebtaqhskjr95kzbl3avdr2xkeex5mybdq+qwcd97drtacxhn1moyrt16pa2tn//v8jy+pf4cs/vwerzu9sday1gd2xf4f/azqlpeb9836lwaaaabjru5erkjggg==)  no-repeat center center;                      cursor: pointer;                    }                    tr.shown td.details-control {                      background: url(data:image/png;base64,ivborw0kggoaaaansuheugaaabqaaaaucayaaacnir0naaacduleqvr4aa2v30ttyrjhvsgsoqkhxpuplkzmlimiiig/pggiidecbadqyc4kf9zvhvdeelx33qncbtyvxzsxxkoqkxiz1szdfudmb5xo5/bt+fa+spcw3ivf+pa+532e5ytn53lfk0qosrggxbaucbukxtxjjjvnq1ixxxfucxeefqgdmoyec6zrtzx/m6swrgv1hmhcdwqclxojxm9cozanjlnhhgt0bbxdvg1cem4klp/p9ykxyx2jhjhjdwvzc9quwuwhzufwdmvisc8qfq4pcbcygvt0njldw0gndsh96deyfj8kmqwo1rjhem8od2vapx/sxlao9aqi/n4e9hywsdmwgarxd2dh7zzyren5ezxyfqhgmohnr3bvesnn216v98hf3yqxg/x0cx719yfs9/wqujfpgtkzz2fbwvz4pb6dhtqrokaol7/0gqlm2hq2enpsxmmpvf3vvvd8uojxv42uet1wy7j+m5mam8p37u6ysm7mgdjnm8mrul5qydtorez+gb3fzlcxnjs7uurmk/jygkhsnnuo57twzhgtw0hho0eprdpv/tvickgjudfqv/lu7q7jzhxqcl9dlqgtsjtl4vj80wvc8xd2v9yfrubmlzpp5wvstltyaswt+lmt1tiskh5q/vfqbgotl6gntk7iq3oz4fsru8ufutqdbjhxceqz+2ape/8zm+jgh8phnxblt7yqnqysnzvivbej7wxgiizejizwei2c4mfgr/aoknn0jk0tiwfpste4ihcn9xbuamcn/n5sly7ikjk8fftqikfvfc4h9lawdx2luqltadeu9/o664ltiovfsof4l+apb5yaiwyn8+8aaaaasuvork5cyii=)   no-repeat center center;                      cursor: pointer;                    }                  </style>                  </div>                <div role="tabpanel" class="tab-pane" id="pacingmodalphotos">                      <div class="container">                          <div class="row" id="fullclass">                      <div class="col-lg-12" style="padding-left: 0px !important; margin-bottom: 10px;">                          <h5 style="vertical-align: middle; text-align: center; color: black; font-size: 16px; font-weight: bold; text-transform: uppercase;">photos</h5>                        <div id="slidercontainer2">                        </div>                        <div id="selectcontainer2">                          <h5>please search photos.</h5>                        </div>                        <div id="loadingcontainer2" style="vertical-align: central; text-align: center;">                          <img src="/images/loading.gif" />                          <br />                            <span class="load">loading...</span>                        </div>                      </div>                    </div>                        </div>                </div>              </div>                <p id="loading" style="text-align: center; vertical-align: central;">                <img src="/images/loading.gif" />                <br />                <span>loading.</span>              </p>            </div>            <div class="modal-footer">              <button type="button" class="btn btn-primary" data-dismiss="modal">close</button>            </div>          </div>        </div>      </div>    </div>  </body>    </html>

links

see jquery datatables – column width issues bootstrap tabs solution common problems jquery datatables , bootstrap tabs.


Comments

Popular posts from this blog

OpenCV OpenCL: Convert Mat to Bitmap in JNI Layer for Android -

python - How to remove the Xframe Options header in django? -

android - org.xmlpull.v1.XmlPullParserException: expected: START_TAG {http://schemas.xmlsoap.org/soap/envelope/}Envelope -