Aria Tag Datatables

0

I have a problem with a table where I need to sort each one by its specific column. Here is the table

<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>

The code that I show you below is the complete part belonging to the table of my javascript where I would have to insert the corresponding data to be able to sort it, the question is that I do not know what to do so that my columns individually are ordered each time that I click on the header of some of them, that's the Aryan label of the datatable plúgin

<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>

This is the complete script code.

    
asked by Miguel C 17.04.2018 в 12:02
source

1 answer

0

The problem is that you are defining columns 0 to 16 as unordered:

"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.

Removing that property will work for you.

I leave here a working example

    
answered by 17.04.2018 / 12:17
source