Dean.DePue
Dean.DePue

Reputation: 1013

Create dropdown in DataTables with event action

I have a table with one column like this:

{
                 "render": function(d,t,r){
                     var $select = $("<select></select>", {
                         "id": r[0]+"start",
                         "value": d
                     });
                     $.each(statuslist, function (Value, Text) {
                         var opt = '<option value=' + Text.Value + '>' + Text.Text + '</option>';
                         if (Text.Text === r[3]){
                             $(opt).prop("selected", true);
                         }
                         $select.append(opt);
                     });
                     $select.attr("id", "opt" + r[0]);
                     $("#opt" + r[0]).on('change', function(){
                         SetStatus(r[0]);
                     });
                     return $select.prop("outerHTML");
                 }
             },

The statuslist is a list of four text-value pairs. The fourth column is the status text of the row and I am trying to make that one selected. Also, I'm trying to capture the event when the value of the select changes. This does not work. Any ideas?

Upvotes: 0

Views: 4834

Answers (1)

Gyrocode.com
Gyrocode.com

Reputation: 58900

There are couple problems

  • You're attaching event handler to the wrong element (idXXX vs XXXstart).
  • You're attaching event handler in the wrong place, render callback can be called multiple times.

I would recommend to move event handler out of your table initialization code.

For example:

$('#example').DataTable({
   // ... skipped ...
   columns: [
      // ... skipped ...
      {            
         "render": function(data, type, full, meta){
            var $select = $('<select/>', { 'class': 'ctrl-status' });
            $.each(statuslist, function (Value, Text) {
               var $opt = $('<option/>', { 'value': Text.Value, 'text': Text.Text });
               if (Text.Text === full[3]){
                  $opt.attr("selected", "selected");
               }
               $select.append($opt);
            });
            return $select.prop("outerHTML");
         }
      }
   ]
});

// Handle change event for status selection control
$('#example').on('change', '.ctrl-status', function(){
    var data = $('#example').DataTable().row($(this).closest('tr')).data();
    SetStatus(data[0]);
});

See this example for code and demonstration.

Upvotes: 3

Related Questions