jquery dataTables - сортировка по диапазону - PullRequest
0 голосов
/ 31 января 2019

У меня есть этот рабочий пример для сортировки таблицы, включая сортировку столбцов.

jsfiddle

$(document).ready(function() {
    // Setup - add a text input to each footer cell
    $('#searchresults thead tr').clone(true).appendTo( '#searchresults thead' );
    $('#searchresults thead tr:eq(1) th').each( function (i) {
        var title = $(this).text();
        // how to create 2 input fields to filter a range (e.g. filter rows where price ranges from 5 to 20)
        if (title == 'price') {
            // how can I do this ?
        }
        $(this).html( '<input type="text" />' );
        $( 'input', this ).on( 'keyup change', function () {
            if ( table.column(i).search() !== this.value ) {
                table
                    .column(i)
                    .search( this.value )
                    .draw();
            }
        } );
    } );
    var table = $('#searchresults').DataTable( {
        orderCellsTop: true,
        fixedHeader: true
    });
});

Мне интересно, как я могу сделать столбец сортируемым с помощьюспектр.В моем примере я хочу иметь 2 поля ввода («от» и «до») для столбца «цена», чтобы отображать только те элементы таблицы, цена которых составляет, например, от 5 до 20.

Ответы [ 2 ]

0 голосов
/ 04 февраля 2019

Вот мое окончательное решение: jsfiddle

$.fn.dataTable.ext.search.push(

    function( settings, data, dataIndex ) {

        var min_id = parseInt( $('#min_id').val(), 10 );
        var max_id = parseInt( $('#max_id').val(), 10 );
        var id = parseFloat( data[0] ) || 0; // use data for the id column

        var min_price = parseInt( $('#min_price').val(), 10 );
        var max_price = parseInt( $('#max_price').val(), 10 );
        var price = parseFloat( data[1] ) || 0;

				var title = $('#title').val();
        var title_data = data[2] || '';
        
        if (
               (
                ( isNaN( min_id ) && isNaN( max_id ) ) ||
                ( isNaN( min_id ) && id <= max_id ) ||
                ( min_id <= id   && isNaN( max_id ) ) ||
                ( min_id <= id   && id <= max_id )
               )
            && (
                ( isNaN( min_price ) && isNaN( max_price ) ) ||
                ( isNaN( min_price ) && price <= max_price ) ||
                ( min_price <= price   && isNaN( max_price ) ) ||
                ( min_price <= price   && price <= max_price )
               )
            && (
                ( title == '' ) ||
                ( title != '' && title_data.toLowerCase().includes(title.toLowerCase()) )
               )               
            )
        {
            return true;
        }

        return false;

    }
);

$(document).ready(function() {
    var table = $('#searchresults').DataTable( {
        orderCellsTop: true,
        fixedHeader: true,
        paging: false,
        language: {
                url: '//cdn.datatables.net/plug-ins/1.10.19/i18n/German.json'
        }
    });   

    // Event listeners to the two range filtering inputs to redraw on input
    $('#min_id, #max_id').keyup( function() {
        table.draw();
    } );
    $('#min_price, #max_price').keyup( function() {
        table.draw();
    } );
    $('#title').keyup( function() {
        table.draw();
    } );    
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/fixedheader/3.1.5/js/dataTables.fixedHeader.min.js"></script>

<table class="datatable" id="searchresults">
 <thead>
  <tr>
    <th>id</th>
    <th>price</th>
    <th>title</th>
  </tr>
   <tr role="row">
     <th>
       <div style="white-space:nowrap;">
         <input type="text" id="min_id" name="min_id" size="3" placeholder="from">
         <input type="text" id="max_id" name="max_id" size="3" placeholder="to">
       </div>
     </th>
     <th>
       <div style="white-space:nowrap;">
         <input type="text" id="min_price" name="min_price" size="3" placeholder="from">
         <input type="text" id="max_price" name="max_price" size="3" placeholder="to">
       </div>
     </th>   
     <th>       
       <input type="text" id="title" name="title" size="10">
     </th>      
   </tr>  
 </thead> 
 <tbody>
  <tr>
    <td>1</td>
    <td>3</td>
    <td>candies</td>
  </tr>
  <tr>
    <td>2</td>
    <td>6</td>
    <td>book</td>
  </tr>
  <tr>
    <td>3</td>
    <td>25</td>
    <td>mouse</td>
  </tr>
  <tr>
    <td>4</td>
    <td>29</td>
    <td>keyboard</td>
  </tr>   
  <tr>
    <td>5</td>
    <td>19</td>
    <td>red wine</td>
  </tr>  
  <tr>
    <td>6</td>
    <td>16</td>
    <td>white wine</td>
  </tr>   
  <tr>
    <td>7</td>
    <td>29</td>
    <td>red wine</td>
  </tr>  
  <tr>
    <td>8</td>
    <td>49</td>
    <td>red wine</td>
  </tr> 
  <tr>
    <td>9</td>
    <td>29</td>
    <td>white wine</td>
  </tr>   
 </tbody>
</table>

Если таблица результатов получила сотни записей, то при наборе текста происходит небольшая задержка.Я пытаюсь сделать это немного более плавным.

0 голосов
/ 01 февраля 2019

вы допустили ошибку в скобках

if ( (( isNaN( min_id ) && isNaN( max_id ) ) || ( isNaN( min_id ) && id <= max_id ) || ( min_id <= id && isNaN( max_id ) ) || ( min_id <= id && id <= max_id )) && (( isNaN( min_price ) && isNaN( max_price ) ) || ( isNaN( min_price ) && price <= max_price ) || ( min_price <= price && isNaN( max_price ) ) || ( min_price <= price && price <= max_price )) ) Также вам нужно изменить id =>min_vol, min_price && max_vol, max_price

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...