0

tengo un problema con una tabla donde se me precisa ordenarlas cada una por su columna especifica. He aquí la tabla

<div class="container-fluid container-fullw padding-bottom-10 scroll-tabla">
<div class="row">
    <table class="table table-striped table-bordered table-hover table-full-width .scroll-tabla" id="personal">
        <thead>
            <tr>
                <th>ID</th>
                <th>Fecha alta</th>
                <th>Nombre</th>
                <th>Apellidos</th>
                <th>DNI</th>
                <th>Seg social</th>
                <th>Año nacimiento</th>
                <th>Móvil</th>
                <th>Teléfono</th>
                <th>Provincia</th>
                <th>Localidad</th>
                <th>Profesión</th>
                <th>Vehículo</th>
                <th>Activo</th>
                <th>Foto</th>
                <th>Colocación</th>
                <th>Modificar</th>

            </tr>
        </thead>
        <tfoot>
            <tr>
                <th></th>
                <th></th>
                <th data-value='<?=$_SESSION[' nombre ']?>'></th>
                <th></th>
                <th></th>
                <th></th>
                <th></th>
                <th></th>
                <th></th>
                <th data-option='select_provincias'></th>
                <th data-option='select_localidades'></th>
                <th data-option='select_profesiones'></th>
                <th data-option='no_buscar'></th>
                <th data-option='no_buscar'></th>
                <th data-option='no_buscar'></th>
                <th data-option='no_buscar'></th>
                <th data-option='no_buscar'></th>
            </tr>
        </tfoot>
        <tbody style="text-align:center">
        </tbody>
    </table>

El código que les muestro a continuación es la parte completa perteneciente a la tabla de mi javascript donde tendría que insertar los datos correspondientes para poder ordenarla, la cuestión es que ya no se que hacer para que mis columnas individualmente se ordenen cada vez que yo haga click sobre la cabecera de alguna de ellas, he ahí la etiqueta aria del plúgin datatables

<script>
//Esto te mete en un array todas las busquedas que hay en la variable de sesion busqueda_personal
var busquedas=[<?php
for($i=0;$i<16;$i++){
    echo '"'.$_SESSION['busqueda_personal']['sSearch_'.$i].'",';
}
?>];

var table;
var contador=0;
$(document).ready(function() {
	$('#personal tfoot th').each( function () {
        var title = $(this).text();
        var tipo=$(this).attr('data-option');
        if(tipo!='no_buscar'){
            if(tipo=='select_provincias'){
                $(this).html( '<select name="search_provincias" id="filtro-search_provincias" onChange="cargaProvincias2(this.value);table.draw();">'+'<?php
        				echo '<option value="">Todas las provincias</option>';
        				$sql4 = 'SELECT id,opcion FROM personal_provincia where relacion=11'; //Sólo se buscan provincias españolas
            		    $rs4 = $bd->consultar($sql4) or die(mysql_error());
        				while($registro=mysql_fetch_row($rs4)){
        				    echo '<option value="' . utf8_encode($registro[0].'">'.$registro[1]).'</option>';
        				}
        			?>'+'</select>' );
            }else if (tipo=='select_localidades'){
                $(this).html( '<select name="search_localidades" id="filtro-search_localidades" onChange="table.draw();"><option selected value="">Todas las localidades</option></select>' );
            }else if (tipo=='select_profesiones'){
                $(this).html( '<select name="search_profesiones" id="filtro-search_profesiones" onChange="table.draw();">'+'<?php
                        echo '<option value="">Todas las profesiones</option>';
                        $sql2 = 'SELECT id, opcion FROM personal_profesion_esp';
                		$rs2 = $bd->consultar($sql2) or die(mysql_error());
                        while($registro2=mysql_fetch_row($rs2)){
        					echo '<option value="' . utf8_encode($registro2[0].'">'.$registro2[1]).'</option>';
        				}
                    ?>'+'</select>' );
            }else{
                var valor=$(this).attr('data-value');
                if(valor==undefined){
                    valor=busquedas[contador];
                }//valor='';
                //$(this).html( '<input type="text" placeholder="Buscar '+title+'" />' );
	        	$(this).html( '<input type="text" value="'+valor+'"/>' );
                contador++;
            }
        }
    } );

     table = $('#personal');
     if(table[0]!=undefined){
	     table=table.DataTable({
	     "language":{
		    "sProcessing":     "Procesando...",
		    "sLengthMenu":     "Mostrar _MENU_ registros",
		    "sZeroRecords":    "No se encontraron resultados",
		    "sEmptyTable":     "Ningún dato disponible en esta tabla",
		    "sInfo":           "Mostrando registros del _START_ al _END_ de un total de _TOTAL_ registros",
		    "sInfoEmpty":      "Mostrando registros del 0 al 0 de un total de 0 registros",
		    "sInfoFiltered":   "(filtrado de un total de _MAX_ registros)",
		    "sInfoPostFix":    "",
		    "sSearch":         "Buscar:",
		    "sUrl":            "",
		    "sInfoThousands":  ",",
		    "sLoadingRecords": "Cargando...",
		    "oPaginate": {
		        "sFirst":    "Primero",
		        "sLast":     "Último",
		        "sNext":     "Siguiente",
		        "sPrevious": "Anterior"
		    },
		    "oAria": {
		        "sSortAscending":  ": Activar para ordenar la columna de manera ascendente",
		        "sSortDescending": ": Activar para ordenar la columna de manera descendente"
		    }
		}/*<--- Esta propiedad provoca que no funcione el ordernar por columnas*/,
		"sAjaxSource": "cargas.php",
        "bProcessing": true,
        "bServerSide": true,
        "fnServerData": function ( sSource, aoData, fnCallback ) {
	        var columnas=['id_per','fecha','nombre','apell1','documento','segsoc','anio_nac','movil','telefono','provincia','localidad','especialidad','vehiculo','activo','','',''];
	        aoData.push({'name':"form_ajax",'value': "dataTable-completas"});

            //SELECTS BUSQUEDAS INDIVIDUALES
            //Provincia
            var provincia=$('#filtro-search_provincias').val();
            aoData.push({'name':"search_provincias",'value': provincia});

            //Localidad
            var localidad=$('#filtro-search_localidades').val();
            aoData.push({'name':"search_localidades",'value': localidad});

            //Profesión
            var profesion=$('#filtro-search_profesiones').val();
            aoData.push({'name':"search_profesiones",'value': profesion});

            //FILTRO
            //Sexo
            var sexo=$('#filtro input[name=sexo]:checked').val();
            aoData.push({'name':"sexo",'value': sexo});

            //Edad desde - Edad hasta
            var edad_desde=$('#filtro-edad_desde').val();
            aoData.push({'name':"edad_desde",'value': edad_desde});
            var edad_hasta=$('#filtro-edad_hasta').val();
            aoData.push({'name':"edad_hasta",'value': edad_hasta});

            //Idioma
            var idioma=$('#filtro-idioma').val();
            aoData.push({'name':"idioma",'value': idioma});

            //Nivel idioma
            var nivelidioma=$('#filtro-nivelidioma').val();
            aoData.push({'name':"nivelidioma",'value': nivelidioma});

            //Discapacidad
            var discapacidad=$('#filtro-discapacidad').val();
            aoData.push({'name':"discapacidad",'value': discapacidad});

            //Vehículo
            if($('#filtro input[name=vehiculo]:checked').val()){
                var vehiculo=$('#filtro-vehiculo').val();
                aoData.push({'name':"vehiculo",'value': vehiculo});
            }

            //Validado (Funciona alreves)
            if($('#filtro input[name=validado]:checked').val()){
                var validado=$('#filtro-validado').val();
                aoData.push({'name':"validado",'value': validado});
            }

            //Activo (Funciona alreves)
            if($('#filtro input[name=activo]:checked').val()){
                var activo=$('#filtro-activo').val();
                aoData.push({'name':"activo",'value': activo});
            }

            //Trabajado
            if($('#filtro input[name=trabajado]:checked').val()){
                var trabajado=$('#filtro-trabajado').val();
                aoData.push({'name':"trabajado",'value': trabajado});
            }

            //Ordenado por
            if(!($('#filtro input[name=ordtrabajado]:checked').val())){
                var ordtrabajado=$('#filtro-ordtrabajado').val();
                aoData.push({'name':"ordtrabajado",'value': ordtrabajado});
            }
            // FIN FILTRO

            $.each( columnas, function( key, value ) {
			  aoData.push({'name':"columnas[]",'value': value});
			});

			$.ajax({
				"dataType": 'json',
				"type": "POST",
				"url": sSource,
				"data": aoData,
				"success": fnCallback
			});
		}
    });

    table.columns().every( function () {
        var that = this;
        $( 'input', this.footer() ).on( 'keyup change', function () {
            if ( that.search() !== this.value ) {
                that
                    .search( this.value )
                    .draw();
            }
        } );
    } );
   }
});




function tablaEjemplo(){

	var oTable = $('#sample_1').DataTable({
		"aoColumnDefs" : [{
			"aTargets" : [0]
		}],
		"aaSorting" : [[1, 'asc']],
		"aLengthMenu" : [[5, 10, 15, 20, -1], [5, 10, 15, 20, "All"] // change per page values here
		],
		// set the initial value
		"iDisplayLength" : 10,
	});
	$('#sample_1_wrapper .dataTables_filter input').addClass("form-control input-sm").attr("placeholder", "Buscar");
	// modify table search input
	$('#sample_1 tfoot th').each( function () {
    	var title = $(this).text();
    $(this).html( '<input type="text" placeholder="Buscar '+title+'" />' );
	} );

    	// Apply the search
    oTable.columns().every( function () {
        var that = this;

        $( 'input', this.footer() ).on( 'keyup change', function () {
            if ( that.search() !== this.value ) {
                that
                    .search( this.value )
                    .draw();
            }
        } );
    } );

	$('#sample_1_wrapper .dataTables_length select').addClass("m-wrap small");
	// modify table per page dropdown
	$('#sample_1_wrapper .dataTables_length select').select2();
	// initialzie select2 dropdown
	$('#sample_1_column_toggler input[type="checkbox"]').change(function() {
		/* Get the DataTables object again - this is not a recreation, just a get of the object */
		var iCol = parseInt($(this).attr("data-column"));
		var bVis = oTable.fnSettings().aoColumns[iCol].bVisible;
		oTable.fnSetColumnVis(iCol, ( bVis ? false : true));
	});
}




/*

	    "language":{
		    "sProcessing":     "Procesando...",
		    "sLengthMenu":     "Mostrar _MENU_ registros",
		    "sZeroRecords":    "No se encontraron resultados",
		    "sEmptyTable":     "Ningún dato disponible en esta tabla",
		    "sInfo":           "Mostrando registros del _START_ al _END_ de un total de _TOTAL_ registros",
		    "sInfoEmpty":      "Mostrando registros del 0 al 0 de un total de 0 registros",
		    "sInfoFiltered":   "(filtrado de un total de _MAX_ registros)",
		    "sInfoPostFix":    "",
		    "sSearch":         "Buscar:",
		    "sUrl":            "",
		    "sInfoThousands":  ",",
		    "sLoadingRecords": "Cargando...",
		    "oPaginate": {
		        "sFirst":    "Primero",
		        "sLast":     "Último",
		        "sNext":     "Siguiente",
		        "sPrevious": "Anterior"
		    },
		    "oAria": {
		        "sSortAscending":  ": Activar para ordenar la columna de manera ascendente",
		        "sSortDescending": ": Activar para ordenar la columna de manera descendente"
		    }
		},
		"aoColumnDefs": [
	      { "bSortable": false, "aTargets": [ 6 ] }
	    ],
		"sAjaxSource": "cargas.php",
		//gestion_clientes_paginas2.php
        "fnServerParams": function ( aoData ) {
          aoData.push( { "form_ajax": "dataTable-usuarios" } );
        },
        "bProcessing": true,
        "bServerSide": true
	*/
</script>

Este es el código completo del script.

1 respuesta 1

0

El problema es que estás definiendo las columnas 0 a 16 como no ordenables:

"aoColumnDefs": [
              { "bSortable": false, "aTargets": [ 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16 ] }
            ]

aoColumnDefs: This array allows you to target a specific column, multiple columns, or all columns, using the aTargets property of each object in the array

bSortable

Enable or disable sorting on this column.

Quitando esa propiedad te funcionará.

Te dejo aquí un ejemplo funcionando

5
  • He intentado probar lo que me has dicho pero no funciona
    – Miguel C
    el 17 abr. 2018 a las 10:34
  • ¿Puedes editar la pregunta y poner el javascript completo donde llamas a datatable?
    – Kiko_L
    el 17 abr. 2018 a las 10:35
  • modificado con el script completo donde llamo a la tabla
    – Miguel C
    el 17 abr. 2018 a las 10:41
  • No termino de verlo... entiendo que no te lanza ningún error la consola, ¿no?
    – Kiko_L
    el 17 abr. 2018 a las 10:52
  • no me lanza ningun error
    – Miguel C
    el 17 abr. 2018 a las 11:14

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.