How to make datatable row or cell clickable?

前端 未结 5 1513
梦谈多话
梦谈多话 2020-12-02 17:10

I\'m working on a history development of a particular user and I want it to be done with dataTables. However, I cannot find the way with which I can make my row or a particu

5条回答
  •  自闭症患者
    2020-12-02 17:42

    To activate click on cell you must use a delegated event handler - this will work on any dataTable :

    $('.dataTable').on('click', 'tbody td', function() {
    
      //get textContent of the TD
      console.log('TD cell textContent : ', this.textContent)
    
      //get the value of the TD using the API 
      console.log('value by API : ', table.cell({ row: this.parentNode.rowIndex, column : this.cellIndex }).data());
    })
    

    Retrieving data of a clicked row can be done by

    $('.dataTable').on('click', 'tbody tr', function() {
      console.log('API row values : ', table.row(this).data());
    })
    

    If you want to send row content via AJAX you should transform the array to an object, and then include it as data :

    $('.dataTable').on('click', 'tbody tr', function() {
      var data = table.row(this).data().map(function(item, index) {
         var r = {}; r['col'+index]=item; return r;
      })
      //now use AJAX with data, which is on the form [ { col1 : value, col2: value ..}]
      $.ajax({
        data: data,
        url: url,
        success: function(response) {
           ...
        }
    })
    

    If you just want a plain link in a cell with target: _blank you can use render :

    columns: [
      { title: "Patient ID", class: "center", render: function(data, type, full, meta) {
         return 'Show patient'
      }
    },
    

提交回复
热议问题