Debug School

rakesh kumar
rakesh kumar

Posted on • Updated on

How to filter data in laravel blade file using javascript and jquery

Filter on input type
Filter by button click
Filter by datepicker
How to apply pagination using datatable

Filter on input type

you want to filter data in a Laravel Blade file using JavaScript, you can create a simple example where you have a list of items and you want to filter them based on a specific criterion when a user interacts with a filter input. Here's an example:

Display Data in Blade:

@foreach ($items as $item)
    <div class="item">{{ $item }}</div>
@endforeach
Enter fullscreen mode Exit fullscreen mode

Add an Input for Filtering:
Add an input field where users can enter the filter criterion:

<input type="text" id="filterInput" placeholder="Enter filter text">
Enter fullscreen mode Exit fullscreen mode

JavaScript Code for Filtering:

<script>
    document.addEventListener('DOMContentLoaded', function () {
        // Select the filter input
        var filterInput = document.getElementById('filterInput');

        // Select all item elements
        var itemElements = Array.from(document.querySelectorAll('.item'));

        // Attach an event listener to the filter input
        filterInput.addEventListener('input', function () {
            // Get the filter text from the input
            var filterText = filterInput.value.toLowerCase();

            // Show or hide items based on the filter text
            itemElements.forEach(function (itemElement) {
                var itemText = itemElement.innerText.toLowerCase();

                if (itemText.includes(filterText)) {
                    itemElement.style.display = 'block';
                } else {
                    itemElement.style.display = 'none';
                }
            });
        });
    });
</script>
Enter fullscreen mode Exit fullscreen mode

jquery code for Filtering

<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
<script>
    $(document).ready(function () {
        // Select the filter input
        var filterInput = $('#filterInput');

        // Select all item elements
        var itemElements = $('.item');

        // Attach an event listener to the filter input
        filterInput.on('input', function () {
            // Get the filter text from the input
            var filterText = filterInput.val().toLowerCase();

            // Show or hide items based on the filter text
            itemElements.each(function () {
                var itemText = $(this).text().toLowerCase();

                if (itemText.includes(filterText)) {
                    $(this).css('display', 'block');
                } else {
                    $(this).css('display', 'none');
                }
            });
        });
    });
</script>
Enter fullscreen mode Exit fullscreen mode

This script listens for changes in the filter input and dynamically hides or shows items based on whether their text includes the filter text.

How to apply pagination using datatable

<!-- Include jQuery -->
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>

<!-- Include DataTables CSS and JS -->
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.25/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.25/js/jquery.dataTables.js"></script>

<div id="paginationContainer">
    @foreach ($items as $item)
        <div class="item">{{ $item }}</div>
    @endforeach
</div>

<input type="text" id="filterInput" placeholder="Enter filter text">

<!-- DataTables Pagination -->
<script>
    $(document).ready(function() {
        // Initialize DataTable with pagination
        var dataTable = $('#paginationContainer').DataTable();

        // Select the filter input
        var filterInput = $('#filterInput');

        // Attach an event listener to the filter input
        filterInput.on('input', function() {
            // Get the filter text from the input
            var filterText = filterInput.val().toLowerCase();

            // Use DataTables API to search and redraw the table
            dataTable.search(filterText).draw();
        });
    });
</script>
Enter fullscreen mode Exit fullscreen mode

=============Practical Examples==========================
In blade file add input filter

  <div class="container mt-5" style="margin-right:90px">
    <div class="card">
        <div class="card-body">
            <h5 class="font-weight-bold text-danger">Filter by Status</h5>                   

            <input type="text" class="form-control mt-2" id="filterInput" style="font-size:18px; border:1px solid blue;" placeholder="Enter filter text">
            <h5 class="card-title mt-2">Orders Detail</h5>               

            <table class="table mt-2" id="orderTable">
                <span id="completion-message" style="color:black;" aria-hidden="true"></span>
                <thead>
                    <tr>
                    <th class="sortable" data-sort="publisher">Publisher name (sort by)  <span id="publisherSortIndicator">&#x2195;</span></th>
                    <th class="sortable" data-sort="status">Influencer Name  (sort by) <span id="publisherSortIndicator">&#x2195;</span></th>
                        <th>Cart Id</th>
                        <th class="sortable" data-sort="status">Status (sort by) <span id="publisherSortIndicator">&#x2195;</span></th>
                        <th>Amount</th>
                        <th class="sortable" data-sort="status">paydate (sort by) <span id="publisherSortIndicator">&#x2195;</span></th>
                    </tr>
                </thead>
                <tbody id="tableBody">
                    @foreach($total_order as $user) 
                        <tr  data-status="{{ strtolower($user->status) }}">
                            <td>{{ $user->user_name }}</td>
                            <td>{{ $user->slug }}</td>
                            <td>{{ strlen($user->order_cart_id) > 10 ? substr($user->order_cart_id, 0, 10) . '...' : $data->order_cart_id }}</td>
                            <td>{{ $user->status }}</td>
                            <td>{{ $user->pay_amount }}</td>
                            <td>{{ $user->order_pay_date }}</td>
                            <td></td>
                        </tr>
                    @endforeach
                </tbody>
            </table>                 
        </div>             
    </div>
</div>
Enter fullscreen mode Exit fullscreen mode

output

Image description

In jquery

<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
    <script>
        $(document).ready(function () {
            console.log("data is coming");

            // Select all table rows
            var tableRows = $('#tableBody tr');

            // Function to get the index of the specified column
            function getColumnIndex(column) {
                return $('#orderTable th[data-sort="' + column + '"]').index();
            }

            var filterInput = $('#filterInput');

            // Attach an event listener to the filter input
            filterInput.on('input', function () {
                console.log("data is coming");
                // Get the filter text from the input
                var filterText = filterInput.val().toLowerCase();

                // Show or hide rows based on the filter text
                tableRows.each(function () {
                    var rowText = $(this).text().toLowerCase();

                    if (rowText.includes(filterText)) {
                        $(this).css('display', 'table-row'); // Show the row
                    } else {
                        $(this).css('display', 'none'); // Hide the row
                    }
                });
            });
        });
    </script>
Enter fullscreen mode Exit fullscreen mode

output

Image description

Filter by button click

In blade file add input filter

  <div class="container mt-5" style="margin-right:90px">
    <div class="card">
        <div class="card-body">
            <h5 class="font-weight-bold text-danger">Filter by Status</h5>                   
                  <button class="btn btn-primary" onclick="filterRows('completed')">Complete</button>
          <button class="btn btn-warning" onclick="filterRows('pending')">Pending</button>
          <button class="btn btn-danger" onclick="filterRows('rejected')">Rejected</button>
          <button class="btn btn-danger" onclick="filterRows('not approved')">Not Approved</button>  
            <input type="text" class="form-control mt-2" id="filterInput" style="font-size:18px; border:1px solid blue;" placeholder="Enter filter text">
            <h5 class="card-title mt-2">Orders Detail</h5>               

            <table class="table mt-2" id="orderTable">
                <span id="completion-message" style="color:black;" aria-hidden="true"></span>
                <thead>
                    <tr>
                    <th class="sortable" data-sort="publisher">Publisher name (sort by)  <span id="publisherSortIndicator">&#x2195;</span></th>
                    <th class="sortable" data-sort="status">Influencer Name  (sort by) <span id="publisherSortIndicator">&#x2195;</span></th>
                        <th>Cart Id</th>
                        <th class="sortable" data-sort="status">Status (sort by) <span id="publisherSortIndicator">&#x2195;</span></th>
                        <th>Amount</th>
                        <th class="sortable" data-sort="status">paydate (sort by) <span id="publisherSortIndicator">&#x2195;</span></th>
                    </tr>
                </thead>
                <tbody id="tableBody">
                    @foreach($total_order as $user) 
                        <tr  data-status="{{ strtolower($user->status) }}">
                            <td>{{ $user->user_name }}</td>
                            <td>{{ $user->slug }}</td>
                            <td>{{ strlen($user->order_cart_id) > 10 ? substr($user->order_cart_id, 0, 10) . '...' : $data->order_cart_id }}</td>
                            <td>{{ $user->status }}</td>
                            <td>{{ $user->pay_amount }}</td>
                            <td>{{ $user->order_pay_date }}</td>
                            <td></td>
                        </tr>
                    @endforeach
                </tbody>
            </table>                 
        </div>             
    </div>
</div>
Enter fullscreen mode Exit fullscreen mode

Image description

In jquery

<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
    <script>
        $(document).ready(function () {
            console.log("data is coming");

            // Select all table rows
            var tableRows = $('#tableBody tr');

            // Function to filter rows based on status
            window.filterRows = function (status) {
                console.log("Filtering rows by status:", status);

                // Show or hide rows based on the filter status
                tableRows.each(function () {
                    var rowStatus = $(this).data('status');
                    console.log("Filtering rows by rowStatus:", rowStatus);
                    if (rowStatus === status) {
                        $(this).css('display', 'table-row'); // Show the row
                    } else {
                        $(this).css('display', 'none'); // Hide the row
                    }
                });
            };

        });
    </script>
Enter fullscreen mode Exit fullscreen mode

output
before click

Image description

after click

Image description

Filter by datepicker

In blade file add input filter

  <div class="col-md-12 col-lg-12" id="name_form">
        <div class="container mt-5">
            <div class="card h-100">
                <div class="card-body">
                <div id="totalEarnings">

    <h5>Total Earnings This Year: <span id="totalThisYear"></span><span></span>||   Month: <span  id="totalThisMonth"></span><span></span>  ||Week: <span id="totalThisWeek"></span></h5>
                </div>
                <h5 class="font-weight-bold text-secondary">Wallet Statement</h5> 
                <h5 class="font-weight-bold text-secondary">Total Amount:{{ $order_sums }}</h5>                   
                <div id="filterButtons">
                <button data-filter="all" onclick="updateFilter('all')">All</button>
                <button data-filter="week" onclick="updateFilter('week')">Week</button>
                <button data-filter="month" onclick="updateFilter('month')">Month</button>
                <button data-filter="year" onclick="updateFilter('year')">Year</button>
            </div>
                <input type="text" class="form-control mt-2" id="filterInput" style="font-size:18px; border:1px solid blue;" placeholder="Enter filter text">
                <div class="row">
            <div class="col-md-6">
                <input type="date" id="dateRangePicker1" class="form-control mydatepicker mt-2" style="font-size:18px; border:1px solid blue;" placeholder="mm/dd/yyyy" name="dateRangePicker1" autocomplete="off">
            </div>
            <div class="col-md-6">
                <input type="date" id="dateRangePicker2" class="form-control mydatepicker1 mt-2" style="font-size:18px; border:1px solid blue;" placeholder="mm/dd/yyyy" name="dateRangePicker2" autocomplete="off">
            </div>
        </div>
              <h5 class="card-title mt-2">Wallet Detail</h5>

                <span id="influencer_result" aria-hidden="true"></span>             
                    <table class="table">
                    <span id="completion-message" style="color:black;" aria-hidden="true"></span>
                        <thead>
                            <tr>
                                <th>No.</th>  
                                <th>Date</th>                              
                                <th>Task Id</th>
                                <th>Publisher</th>                                
                                <th>Amount</th>  
                            </tr>
                        </thead>
                        <tbody id="earningsTableBody">
                        @php
                            $customIndex = 1; // Initialize custom index                            
                        @endphp
                        @foreach($walletsharedata as $data) 
                            <tr>
                               <td>{{$customIndex}}</td>
                                <td>{{ $data->order_pay_date }}</td>                                
                                <td>{{ 'task_' . $data->id }}</td>   
                                <td>{{ $data->slug }}</td>  
                                <td>{{ $data->pay_amount }}</td>   
                            </tr>
                            @php
                        $customIndex++; // Increment the custom index
                        @endphp       
                            @endforeach
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
Enter fullscreen mode Exit fullscreen mode

Image description

In jquery

 $('#dateRangePicker1, #dateRangePicker2').on('input', function () {
                            var startDate = $('#dateRangePicker1').val();
                            var endDate = $('#dateRangePicker2').val();
                            var filterType = "custom";
                                updateFilter(filterType);
                              });

        function updateFilter(filterType) {
            // Reset table
            $('#earningsTableBody tr').show();
            // Hide rows not matching the filter type
            if (filterType !== 'all') {
                console.log("data is updateFilter ");
                console.log(filterType);
                $('#earningsTableBody tr').filter(function () {
                    var orderDate = $(this).find('td:eq(1)').text(); // Assuming date is in the second column
                    var filterDate = moment(orderDate); // You need to include the moment.js library for this
                    var currentDate = moment();
                    var momentOrderDate = moment(orderDate, 'MM/DD/YYYY');
                    var startDate = $('#dateRangePicker1').val();
                var endDate = $('#dateRangePicker2').val();
                console.log(startDate);
                console.log(endDate);
                console.log(filterDate);
                    // Check if the order date matches the selected filter type
                    if (filterType === 'week' && !filterDate.isSame(currentDate, 'week')) {
                        $(this).hide();
                    } else if (filterType === 'month' && !filterDate.isSame(currentDate, 'month')) {
                        $(this).hide();
                    } else if (filterType === 'year' && !filterDate.isSame(currentDate, 'year')) {
                        $(this).hide();
                    }
                    else if (filterType === 'year' && !filterDate.isSame(currentDate, 'year')) {
                        $(this).hide();
                    }
                    else if (filterType === 'custom' && (
                        filterDate.isBefore(moment(startDate)) ||
                        filterDate.isAfter(moment(endDate))
                )) {
                    console.log("data is updateFilter custom");
                    $(this).hide();
                } else if (filterType === 'custom' && (
                    filterDate.isBetween(moment(startDate), moment(endDate))
                )) {
        console.log("data is updateFilter customsd");
        // Handle the case where momentOrderDate is between startDate and endDate
        // For example, you may choose to do something specific for this case
        // $(this).doSomethingSpecific();
    }
                });
            }
        }
Enter fullscreen mode Exit fullscreen mode

output
before click

Image description

after click

Image description

Summary

Filter on input type
Select all table rows for particular table using id
selecting an HTML element with the ID "filterInput" using jQuery and storing it in a variable named filterInput
Attach an event listener to the filter input using on input
Get the filter text from the input
iterate over each row in the table collection
extracts the text content of the current row inside for loop of particular table using id
apply conditional statement checking if the rowText includes the filterText
Show or hide rows based on the filter text
Filter by button click
Select all table rows
onclick Function to filter rows based on status
iterate over each row in the table collection
extracts the text content of the status field inside for loop of particular table using id
apply condition if button status is equal to table status field text content that row display only
Filter by datepicker
Date input for start date and end date in html
Display wallet details in a table
Iterate over wallet details and populate the table
Event Listener for Date Inputs while typing date using oninput eventlistener
get startdate and end date value using id
Calls the updateFilter function with the filter type set to "custom."
using find get second col td text content orderdate consider as filterdate
filterdate(orderdate) is between start date and enddate using isBetween
filterdate(orderdate) is after start date and before enddate using isBefore and isAfter
if condition match then Hide rows not matching the filter type using $(this).hide()

How to apply pagination using datatable

Apply filter on input type search

$(document).ready(function () {
    var currentPage = 1;
    var itemsPerPage = 5;

    // Sample data array (replace with your actual data)
    var yourDataArray = [
        // ... your data objects
    ];

    function displayFilteredData(data) {
        var resultContainer = $('#resultContent');
        resultContainer.empty();

        // Add input field for searching
        var searchInput = $('#searchInput');
        var searchValue = searchInput.val().toLowerCase();

        if (data.length > 0) {
            var startIndex = (currentPage - 1) * itemsPerPage;
            var endIndex = startIndex + itemsPerPage;
            var paginatedData = data.slice(startIndex, endIndex);
            var totalPages = Math.ceil(data.length / itemsPerPage);

            // Add pagination controls
            addPaginationControls(totalPages);

            $.each(paginatedData, function (index, item) {
                var cardContent = '<div class="card">';
                // Your existing code ...

                // Apply search filter
                if (searchValue === '' || containsSearchTerm(item, searchValue)) {
                    resultContainer.append(cardContent);
                }
            });
        }
    }

    function containsSearchTerm(item, searchTerm) {
        // Add conditions for search based on your data structure
        // For example, check if item properties contain the search term
        return (
            item.order_id.toString().toLowerCase().includes(searchTerm) ||
            item.cart_id.toString().toLowerCase().includes(searchTerm) ||
            item.influencer_name.toLowerCase().includes(searchTerm) ||
            // Add more conditions as needed
            false
        );
    }

    // Bind the input event to trigger filtering
    $('#searchInput').on('input', function () {
        displayFilteredData(yourDataArray);
    });

    // Function to add pagination controls
    function addPaginationControls(totalPages) {
        // Implement pagination controls if needed
    }

    // Initial display
    displayFilteredData(yourDataArray);
});
Enter fullscreen mode Exit fullscreen mode

Top comments (0)