Home > OS >  Set default value before click event triggers
Set default value before click event triggers

Time:10-10

I have button groups. Once user clicks on the link, it filters value based on the content in the link. By default I added selected class. I want default value of link which contains selected class to be considered for filtering before click event triggers. My detailed code is here - https://codepen.io/deepanshu88/pen/gOxOLeO It works fine when user clicks on c-btn-group but not considers default value when page loads. As of now it shows complete data without filtering when page loads.

<div class="c-btn-group">
  <a class="c-btn selected">Large Cap</a>
  <a class="c-btn">Small Cap</a>
  <a class="c-btn">virginica</a>
</div>

JS

$('.c-btn-group').on('click', 'a', function(event) {
   var searchTerm = this.textContent;

/* 4th column filtering */   
    $.fn.dataTable.ext.search.push(function(settings, data, dataIndex) {
       
 if (data[3] == searchTerm) {return true;}
 return false;
 
   })
  
   table.draw();
   $.fn.dataTable.ext.search.pop();
  
// Add or remove 'selected' class;
event.preventDefault();
$('a').removeClass('selected');
$(this).addClass('selected');       
    });

CodePudding user response:

Try the below script. Here is demo

Separate out logic of dataTable filtering inside filter function. Get selected text by $('.c-btn-group .selected').text(); and call filter(initialSelectedText);

var myList2;

$.ajax({
  url: "https://raw.githubusercontent.com/markwsac/jsonfile/main/jsondata.json",
  type: "get",
  dataType: 'text',
  async: false,
  success: function(response) {
    if (!response) return;

    response = response.slice(0, -1); // trim ";" at the end
    window.myList2 = JSON.parse(response);

  },
  error: function(err) {
    console.log(err);
  }
});

var myList = window.myList2;

$(document).ready(function () {
    table = $("#mfTable").DataTable({
        data: myList,
        paging: true,
        lengthChange: false,
        searching: true,
        info: false,
        columns: [
            { data: 'Fund Name' },
            { data: 'Morningstar Rating' },
            { data: 'Category Rank' },
            { data: 'Category' },   
            { data: 'Expense Ratio' }, 
            { data: 'AUM (Cr)' }, 
            { data: 'NAV' }, 
        ],
            columnDefs: [{
            "defaultContent": "-",
            "targets": "_all"
        }]
    });
    
    const initialSelectedText = $('.c-btn-group .selected').text();
    filter(initialSelectedText);

    $('.c-btn-group').on('click', 'a', function(event) {
        var searchTerm = this.textContent;
        /* 4th column filtering */   
        filter(searchTerm);
        // Add or remove 'selected' class;
        event.preventDefault();
        $('a').removeClass('selected');
        $(this).addClass('selected');  
    });
  
});

function filter(searchTerm){

    $.fn.dataTable.ext.search.push(function(settings, data, dataIndex) {
        if (data[3] == searchTerm) {return true;}
        return false;
    });
    
    table.draw();
    $.fn.dataTable.ext.search.pop();
}

CodePudding user response:

DataTable provides an Option for this. When you are initializing your table, just use the searchCols option which would load the table with the initial search provided. for Example:

  table = $("#mfTable").DataTable({
    data: myList,
    paging: true,
    lengthChange: false,
    searching: true,
    info: false,
        columns: [
                { data: 'Fund Name' },
                { data: 'Morningstar Rating' },
                { data: 'Category Rank' },
                { data: 'Category' },   
                { data: 'Expense Ratio' }, 
                { data: 'AUM (Cr)' }, 
                { data: 'NAV' }, 
            ],
      columnDefs: [{
    "defaultContent": "-",
    "targets": "_all"
  }],
    searchCols: [
         null,
         null,
         null,
         { "search": "Large Cap" },   
         null, 
         null, 
         null, 
            ]
  })

Here is the link for this option https://datatables.net/reference/option/searchCols

You can also use the libraries own search method rather than implementing it yourself, so instead of writing:

$.fn.dataTable.ext.search.push(function(settings, data, dataIndex) {
       
 if (data[3] == searchTerm) {return true;}
 return false;
 
   })
  
   table.draw();
   $.fn.dataTable.ext.search.pop();

just write: table.column(3).search(searchTerm).draw();

  • Related