Click here to Skip to main content
15,507,755 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have a datatable with a Search functionality having 2 input boxes - one to input minimum age and one to input maximum age. The datatable does not have a column age but rather a column DOB in date format. Now I need to search max/min age based on the DOB. For example, I will input 10 in box minimum age and 15 in box maximum age and based on the matching DOB it should return the specific rows. (So far, it works if I have to search the age as an integer when it is already in a column.) Any idea how I can achieve this.


What I have tried:

so far I tried below code but showing no desired results. I know I am missing a lot of logic here.
JavaScript
$.fn.dataTable.ext.search.push(
    function( dateString,settings, data, dataIndex ) {
        var min = parseInt( $('#min').val(), 10 );
        var max = parseInt( $('#max').val(), 10 );
        var age = parseFloat( data[5] ) || 0; // use data for the age column
        var today = new Date();
        var birthDate = new Date(dateString);
        // var age = today.getFullYear() - birthDate.getFullYear();
        var m = today.getMonth() - birthDate.getMonth();
 
        if ( m < 0 || (m === 0 && today.getDate() < birthDate.getDate()) || ( isNaN( min ) && isNaN( max ) ) ||
             ( isNaN( min ) && age <= max ) ||
             ( min <= age   && isNaN( max ) ) ||
             ( min <= age   && age <= max ) )
        {
            return true;
        }
        return false;
    }
);
		    var table = $('#example').DataTable();
     
    // Event listener to the two range filtering inputs to redraw on input
    $('#min, #max').keyup( function() {
        table.draw();
    } );
Posted
Updated 28-Apr-21 5:11am

1 solution

You're overcomplicating this.

You get the current date.
Adjust the year datepart to your min and max range but keep the rest of the current date unchanged.*
Test your table of dates (DOB field) to determine if it's between these dates (inclusive).


(Modify the date object directly - you can make two of them so it's extra easy)


 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900