Custom filter range of number datatables

Asked

Viewed 274 times

1

I’m trying to make a custom filter by selecting a range of numbers with the datatables and it only works once. I tried several ways and none worked and researching found nothing, so I come here to ask for your help.

<select id="filtro1">
            <option value="">Selecione</option>
            <option value="1-10">1-10</option>
            <option value="11-16">11-16</option>
            </select>

here is the jquery

$(document).ready(function() {
    $('#filtro1').on("change", function(){
        var valor = $(this).val();      
        var arr = valor.split('-');

            $.fn.dataTable.ext.search.push(
    function( settings, data, dataIndex ) {
        var min = parseInt( arr[0], 7 );
        var max = parseInt( arr[1], 7 );
        var age = parseFloat( data[7] ) || 0; // use data for the age column

        if ( ( isNaN( min ) && isNaN( max ) ) ||
             ( isNaN( min ) && age <= max ) ||
             ( min <= age   && isNaN( max ) ) ||
             ( min <= age   && age <= max ) )
        {
            return true;
        }
        return false;
    }
);
table.draw();           

    });

var table = $('#classificacao').DataTable({
        "lengthMenu": [ [10, 25, 50, 100, -1], [10, 25, 50, 100, "Todos"] ],
        "processing": true,     
        "oLanguage": {
            "sUrl": "../busca/pt-br.txt"
        },
        "columnDefs": [
            {
                "targets": [ 7 ],
                "visible": false
            }
        ]
    });
});

based on this example that uses input type text

https://datatables.net/examples/plug-ins/range_filtering.html

from now on I appreciate any help.

1 answer

1

I come here with the problem solved and to possibly help other people.

        $('#filtro1').on("change", function(){
        var valor = $(this).val();      
        var arr = valor.split('-');

        if ( $.fn.dataTable.ext.search.length>0 ) {
    $.fn.dataTable.ext.search.pop(); //<--here
  }

            $.fn.dataTable.ext.search.push(
    function( settings, data, dataIndex ) {
        var min = parseInt( arr[0], 7 );
        var max = parseInt( arr[1], 7 );
        var age = parseFloat( data[7] ) || 0; // use data for the age column

        if ( ( isNaN( min ) && isNaN( max ) ) ||
             ( isNaN( min ) && age <= max ) ||
             ( min <= age   && isNaN( max ) ) ||
             ( min <= age   && age <= max ) )
        {
            return true;
        }
        return false;
    }
);
table.draw();           

    });

Browser other questions tagged

You are not signed in. Login or sign up in order to post.