Utilize range slider to refine dataset

I have implemented a jquery datatable along with the range.slider plugin.

My goal is to apply the range slider to filter out data in the last column.

In my attempt, I am using search.push to accomplish this filtering process.

Below is an example of my implementation:

$(document).ready(function() {

  var lowestPriceRange = $("#ion-range");

  /**
   * Lowest Price Range
   */
  lowestPriceRange.ionRangeSlider({
    type: 'double',
    min: 0,
    max: 100,
    from: 0,
    to: 50
  });

  const table = $('.datatable-responsive').DataTable();

  $('#ion-range').on('change', function() {
    var $inp = $(this);
    var min = parseFloat($inp.data("from")); // input data-from attribute
    var max = parseFloat($inp.data("to")); // input data-to attribute

    let search = [];
    console.log(min, max); // all values

    search.push(
      function(settings, data, dataIndex) {
        var col = parseFloat(data[4]) || 0; // data[number] = column number
        if ((isNaN(min) && isNaN(max)) ||
          (isNaN(min) && col <= max) ||
          (min <= col && isNaN(max)) ||
          (min <= col && col <= max)) {
          return true;
        }
        return false;
      }
    );
    table.column(3).search(search, true, false).draw();
  });
});
<!DOCTYPE html>
<html lang="en>">

Despite capturing the event for data filtering, I'm facing an issue where my datatable does not reflect the filtered results.

Any insights or suggestions on what might be causing this discrepancy?

Your feedback and assistance are much appreciated!

Answer №1

Providing guidance on where to insert Georgy's answer in order to successfully execute the question above.

    $(document).ready(function() {

      var lowestPriceRange = $("#ion-range");
 var min=0;
 var max=0;
      /**
       * Setting up the Lowest Price Range
       */
      lowestPriceRange.ionRangeSlider({
        type: 'double',
        min: 0,
        max: 100,
        from: 0,
        to: 50
      });

      const table = $('.datatable-responsive').DataTable();
$.fn.dataTable.ext.search.push(
    function( settings, data, dataIndex ) {
        var age = parseFloat( data[5] ) || 0; // utilizing 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;
    }
);
      $('#ion-range').on('change', function() {
        var $inp = $(this);
         min = parseFloat($inp.data("from")); // retrieving input data-from attribute
         max = parseFloat($inp.data("to")); // accessing input data-to attribute

        let search = [];
        console.log(min, max); // displaying all values

        search.push(
          function(settings, data, dataIndex) {
            var col = parseFloat(data[4]) || 0; // data[number] = specifying column number
            if ((isNaN(min) && isNaN(max)) ||
              (isNaN(min) && col <= max) ||
              (min <= col && isNaN(max)) ||
              (min <= col && col <= max)) {
              return true;
            }
            return false;
          }
        );
        table.column(3).search(search, true, false).draw();
      });
    });

Answer №2

While I couldn't find any information on using filter functions (callbacks) in the search method like you're doing, I did come across an alternative approach to enhance the search functionality.

/* Custom filtering function which will search data in column four between two values */
$.fn.dataTable.ext.search.push(
    function( settings, data, dataIndex ) {
        var min = parseInt( $('#min').val(), 10 );
        var max = parseInt( $('#max').val(), 10 );
        var age = parseFloat( data[3] ) || 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;
    }
);

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

Please note that you have selected the wrong column ('LAST' label is at the 3rd index, as columns start with a 0 index). Hopefully, this information can be helpful to you.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

At what point is the JavaScript function expression triggered in this code snippet?

let express = require('express') let app = express(); app.use(express.static('static')); let server = app.listen(3000, function() { let port = server.address().port; console.log("The server has started on port", port); }); I ...

Using Local Storage to store arrays in JavaScript/jQuery

Currently, I am implementing a set of multiple buttons each containing data-id and data-name Below is my concept along with some sample code for reference: $(".clickCompare").click(function ({ var id = $(this).attr('data-id'); var ...

When using nodejs with sqlite3, the first callback parameter returns the class instance. How can this be resolved in order to prevent any issues?

Exploring a TypeScript class: class Log { public id: number; public text: string; construct(text: string){ this.text = text; } save(){ db.run( `insert into logs(text) values (?) `, this.text, ...

Using jQuery to load and parse a JSON file stored on a local system

I am a beginner in scripting languages and recently searched for ways to load and parse JSON files using jQuery. I found helpful resources on Stack Overflow. The JSON file I am working with is called new.json. { "a": [ {"name":"avc"}, ...

Automatically populating state and city fields with zip code information

Starting out in the world of web development, I encountered a challenge with a registration form I'm constructing for our company. For guidance, I referred to this resource: http://css-tricks.com/using-ziptastic/. This project marks my initial interac ...

How to smoothly transition a div from one location to another using animations in an Ionic3-Angular4 application

I'm attempting to incorporate some animation into my Ionic 3 mobile app. Specifically, I want to shift a div from one location to another. In the code snippet provided below, I am looking to move the div with the "upper" class after the timeline-item ...

React components do not re-render when the context value changes

The issue with React not re-rendering when the context value changes persists I am using tailwindcss, React(v18.2.0), and vite(3.2.4). I have already attempted i want that clicking on TodoItem should change the completed value in the todo using React con ...

Displaying random divs and subsequently animating them downwards using JavaScript

I am in the process of creating a random appearing div that then falls down. Here is the code I have so far: $(document).ready(function(){ $('#test').animate({top: 80 + '%'},900); }); <div id="test" style="background:#98bf21;heigh ...

Error: The function seems to be malfunctioning or missing

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script> <script type="text/javascript"> $('div'); // <--- THIS DOESN'T WORK </script> An issue has been encountere ...

Selecting elements dynamically with JQuery

Trying to use a jQuery selector within plugin code created by a 3rd party has proved difficult. When hardcoded, it works fine; however, when attempting to use variables for dynamic selection, the object cannot be found. The lack of id handles in the CSS c ...

Multiple web pages utilizing Angular app/widget

I have successfully built a chat application similar to Google Hangouts. However, I am facing a challenge with the angular app/widget running on other pages when URL's are changed, causing the app to either remain fixed or restart on the new web page. ...

Retrieving the current day integer from a fullcalendar rendering in JavaScript and utilizing it as an array key

I am currently working on rendering a full calendar and I would like each cell to be displayed in a different color based on an array that contains color values for each day of the month. The array is retrieved in JSON format. Here is an example JSON arra ...

How to bypass validation for required input in jQuery validate plugin

As an example, consider the <input name="surname" id="surname" type="text">. Sometimes I want to hide this input and make it non-required. My current workaround is to set a value such as "some value" when hiding the input, and then remove this value ...

Here are the steps to refresh a div after an AJAX call that contains a form:

After using AJAX, I am reloading a div in the following way: $('.comment_form').on('submit', function(e){ e.preventDefault(); ..... success: function(data) { $('.result').html(data); ...

Obtain the key's value from a JSON object that is nested within another

Managing a complex data structure is crucial in programming. How can I efficiently retrieve specific values using known keys from this nested data? Take, for instance: var data = { code: 42, items: [{ id: 1, category: [{ ...

Check input validations in Vue.js when a field loses focus

So I've created a table with multiple tr elements generated using a v-for loop The code snippet looks like this: <tr v-for="(item, index) in documentItems" :key="item.id" class="border-b border-l border-r border-black text ...

Transmitting JSON data using a Jquery AJAX request in PHP

I'm facing an issue passing a JSON array from a jQuery AJAX call to a PHP file and attempting to write the received data to a file. This is my code: var contacts = [{"address":[],"phone":[],"last_name":"abc","email":[{"address":"<a href="/cdn-cgi/ ...

Navigating a double entry validation in a Java script prompt while utilizing Selenium

Can someone please assist me with the following scenario: I need to complete a double entry check prompt/alert that contains two text boxes. The task is to fill in these two text boxes and then click on the OK button. Potential solutions attempted: I tr ...

Typescript inheritance results in an undefined value being returned

I am trying to understand the code below, as I am confused about its functionality. In languages like C# or Java, using the base or super keyword usually returns values, whereas in TypeScript, I am receiving "undefined". However, when I switch from using " ...

JavaScript validation controls do not function properly when enabled on the client side

Following the requirements, I have disabled all validation controls on the page during the PageLoad event on the server side. When the submit button is clicked, I want to activate the validations and check if the page is valid for submission. If not, then ...