How to insert a select in a table (Datatables)?

2

Use datatables to list data brought from a DB but I need to insert a select (drop-down list) in one column of the rows try this way but it did not work.

var users = $('#users').DataTable(
    {});
    $.ajax({
            url: 'users',
            type: 'POST'
        })
        .done(function(answer) {
            var result= $.parseJSON(answer);    

            for (var i = result.length - 1; i >= 0; i--) 
            {
        .row.add([
                                result[i].id,
                                result[i].nombre,
                                result[i].apellido,
                               '<select><option>-- Seleccione --</option></selec>',
                                '<a class="btn-floating btn-small waves-effect waves-light red hoverable"><i class="material-icons">content_paste</i></a>'
                            ])
                        .draw()
                   .node();
        .fail(function() {
            console.log("error");
        });

How could I fix it?

    
asked by JDavid 28.02.2017 в 16:30
source

3 answers

1

Friend with this code valid that the field you created in the data table and insert the values in the dropdown or failing in the select.

if($(column.footer()).hasClass('groupprices')){
						var select = $('<select><option value=""></option></select>')
								.appendTo($(column.footer()).empty())
								.on( 'change', function () {
									var val = $.fn.dataTable.util.escapeRegex($(this).val());
									//alert($(this).val());
									column.search(val,  false, false, true).draw();
								});

						column.data().unique().sort().each( function ( d, j ) {
							select.append('<option value="'+d+'">'+d+'</option>');
						});
					}
    
answered by 28.02.2017 в 22:58
0

Datatables will not magically know which objects you are trying to add a row to. You must specify it.

   var users = $('#users').DataTable({});

    users.row.add( [ 100, 'Nombre', 'Apellido', '<select><option>Uno</option></select>', 'El link' ] )
    .draw()
    .node();

And make sure you match the number of columns you currently have to the number of columns you're creating in row.add.

    
answered by 28.02.2017 в 18:04
0

You can use "render" in the definition of your column:

In the definitions of your columns:

 "columns": [
    { "data"   : "id" },
    { "data"   : "nombre" },
    { "data"   : "apellido"},
    { "data"   : "select",
      "render" : function ( data, type, row ) {
                       return '<select><option>-- Seleccione --</option></selec>';
                 }
    }
  ]

the "data" parameter refers to the value of the data in that cell (in this case "select") while "row" is an object with which you can access any other property of the object that you bring to insert the row : row.id, row.name, ...

    
answered by 13.12.2018 в 22:27