最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Display Button on condition in Datatables with Cell Value - Stack Overflow

programmeradmin3浏览0评论

I have a Table using Datatables and the last column shows as default value a 0, but it can also show a value >=1 means, as long as it is having a 0 value, it shouldn't do anything, but once it is >=1 than I want to have a button displayed which picks a value from the Datatable and than opens a Modal.

Not sure how to get this Button thing done.

Below is my Datatable code incl. html.

// Manual Modal
$('#myModal').on('shown.bs.modal', function () {
  $('#myInput').focus()
});

// Datatables Code
$(document).ready(function() {
  $('#DTResTableList_1').DataTable({
    "ajax": {
      url: 'data.inc.php',
      method: 'POST',
      dataType: 'json',
      contentType: 'application/json; charset=utf-8',
      dataSrc: ""
    },
    paging: false,
    scrollY: 400,
    select: true,
    'columns': [{
        'data': 'TABLE_NUMBER'
      },
      {
        'data': 'STATION'
      },
      {
        'data': 'GUESTS'
      },
      {
        'data': 'T_STATUS'
      },
      {
        'data': 'MINUTES_SEATED'
      },
      {
        'data': 'MINUTES_OVERDUE'
      }
    ]
  });
  setInterval(function() {
    $('#DTResTableList_1').DataTable().ajax.reload(null, false); // user paging is not reset on reload
  }, 5000);
});
<link href=".0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet" />
<link href=".10.13/css/jquery.dataTables.min.css" rel="stylesheet" />
<script src=".1.1/jquery.min.js"></script>
<script src=".0.0-alpha.6/js/bootstrap.min.js"></script>
<script src=".10.13/js/jquery.dataTables.min.js"></script>


<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal">
  Launch demo modal
</button>

<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

<div class="container-fluid">
  <table class="table table-sm table-striped table-hover" id="DTResTableList_1" style="width: 100%;">
    <thead>
      <tr>
        <th class="" data-toggle="tooltip" data-placement="top" title="Table Number">Table</th>
        <th class="" data-toggle="tooltip" data-placement="top" title="Waiterstation">Station</th>
        <th class="" data-toggle="tooltip" data-placement="top" title="Guests on Table">G</th>
        <th class="" data-toggle="tooltip" data-placement="top" title="Table Stauts">Status</th>
        <th class="" data-toggle="tooltip" data-placement="top" title="Minutes Seated">Minutes</th>
        <th class="" data-toggle="tooltip" data-placement="top" title="Overdue">Button</th>
      </tr>
    </thead>
  </table>
</div>

I have a Table using Datatables and the last column shows as default value a 0, but it can also show a value >=1 means, as long as it is having a 0 value, it shouldn't do anything, but once it is >=1 than I want to have a button displayed which picks a value from the Datatable and than opens a Modal.

Not sure how to get this Button thing done.

Below is my Datatable code incl. html.

// Manual Modal
$('#myModal').on('shown.bs.modal', function () {
  $('#myInput').focus()
});

// Datatables Code
$(document).ready(function() {
  $('#DTResTableList_1').DataTable({
    "ajax": {
      url: 'data.inc.php',
      method: 'POST',
      dataType: 'json',
      contentType: 'application/json; charset=utf-8',
      dataSrc: ""
    },
    paging: false,
    scrollY: 400,
    select: true,
    'columns': [{
        'data': 'TABLE_NUMBER'
      },
      {
        'data': 'STATION'
      },
      {
        'data': 'GUESTS'
      },
      {
        'data': 'T_STATUS'
      },
      {
        'data': 'MINUTES_SEATED'
      },
      {
        'data': 'MINUTES_OVERDUE'
      }
    ]
  });
  setInterval(function() {
    $('#DTResTableList_1').DataTable().ajax.reload(null, false); // user paging is not reset on reload
  }, 5000);
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://cdn.datatables.net/1.10.13/css/jquery.dataTables.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js"></script>
<script src="https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script>


<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal">
  Launch demo modal
</button>

<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

<div class="container-fluid">
  <table class="table table-sm table-striped table-hover" id="DTResTableList_1" style="width: 100%;">
    <thead>
      <tr>
        <th class="" data-toggle="tooltip" data-placement="top" title="Table Number">Table</th>
        <th class="" data-toggle="tooltip" data-placement="top" title="Waiterstation">Station</th>
        <th class="" data-toggle="tooltip" data-placement="top" title="Guests on Table">G</th>
        <th class="" data-toggle="tooltip" data-placement="top" title="Table Stauts">Status</th>
        <th class="" data-toggle="tooltip" data-placement="top" title="Minutes Seated">Minutes</th>
        <th class="" data-toggle="tooltip" data-placement="top" title="Overdue">Button</th>
      </tr>
    </thead>
  </table>
</div>

Share Improve this question asked Apr 16, 2017 at 20:24 CyberCyber 2,7044 gold badges24 silver badges43 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 15

Ok, here is one closer to what you asked for. Here is on that puts buttons in the last column if the employee is under 40. Again, the code gets the data for the row then displays the name of the employee. Notice how I used render in the columnDefs.

http://jsbin.com/gobonec/edit?js,output

$(document).ready(function () {



var table = $('#example').DataTable({
        "data": dataStore.data,
        "columns": [
        { "data": "name" },
        { "data": "age" },
        { "data": "position" },
        { "data": "office" },
        { "data": "extn" },
        { "data": "start_date" },
        { "data": "salary" },
        { "data": null },
        ],
        columnDefs: [{
        // puts a button in the last column
        targets: [-1], render: function (a, b, data, d) {
            if (data.age < 40) {
                return "<button type='button'>Go</button>";
            }
            return "";
        }
    }],

});
table.on("click", "button",
                function () {
                    alert(table.rows($(this).closest("tr")).data()[0].name);

                });

});

From DataTables Callbacks:

fnCreatedRow:

This function is called when a TR element is created (and all TD child elements have been inserted), or registered if using a DOM source, allowing manipulation of the TR element (adding classes etc).

That means you can add such an option when creating DataTable:

"fnCreatedRow": function( nRow, aData, iDataIndex ) {
    if (+aData.MINUTES_OVERDUE > 0) {
        $(nRow).find('td:last')
                .replaceWith('<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal" val="'
                + aData.MINUTES_OVERDUE  + '">Launch demo modal</button>');
    }
},

And changing your modal shown.bs.modal handler to:

$('#myModal').on('shown.bs.modal', function (e) {
    $('#myInput').val($(e.relatedTarget).attr('val')).focus();
});

Explanation: whenever a row is created:

  • test the content of last element
  • if this is greater than 0 replace the table cell with a button having an attribute containing the value of interest

whenever the modal is shown:

  • get the attribute from the related button and put it into the input field

The event handler for shown.bs.modal must be inside the document ready.

I have a solution that uses the in row selector and button extensions. In my sample, if the user is older than 40 the button is both disabled and hidden. if they are younger, its displayed and enabled. Clicking on the button gets the data object and uses it to display the person's name

http://live.datatables.net/kudotiqu/1/edit

  $(document).ready( function () {
      var table = $('#example').DataTable({select:"single",dom:"tB",
                                   buttons:[{text:"Do It", 
                                             extend:"selected",
                                             action:function( e, dt, node, config){
                                             alert(  dt.rows({selected:true}).data()[0][0]);}}]
       });
     table.on( 'select', function ( e, dt, type, indexes ) {
            var s = dt.settings();                                          
           var g = dt.rows(indexes).data()[0] ;  
           if(parseInt(g[3]) > 40)  {
             s.buttons().enable(false);
             $(s.buttons()[0].node).css("display","none");
           } 
           else {
               s.buttons().enable(true);
             $(s.buttons()[0].node).css("display", "");
            } 
         } );

    });
发布评论

评论列表(0)

  1. 暂无评论