implementing a search filter using a search bar with JavaScript, inside a Laravel Blade or HTML file

Our current website is powered by a Laravel blade template, showcasing furniture groups with multiple pieces of furniture in each group. The page is constructed using Laravel's foreach loops for both furniture groups generated by $orderformdata->pgroups and the items within the groups generated by $pgroup->pskus.

We used to have a search bar driven by Angular that enabled live filtering on the page – meaning if you typed 'sofa', anything not related to a sofa would instantly disappear. I am now looking to implement a similar live search functionality without a submit button or action, rather than autocomplete.

I lack expertise in JavaScript but have a JSON encoded variable for these products. I'm considering utilizing JS or JQuery to filter through my foreach loops as an alternative. Below are snippets of the existing JavaScript code on the page, showcasing the JSON object and the non-functional search JS:

<script type = "text/javascript">
var orderFormData = <?php echo json_encode ($tempdata);?>;
</script>
<script>
function myFunction() {
  var input, filter, table, tr, td, i;
  input = document.getElementById("srch-term");
  filter = input.value.toUpperCase();
  table = document.getElementsByClassName("wrapper");
  tr = table.getElementsByTagName("tr");
    for (i = 0; i < tr.length; i++) {
    td = tr[i].getElementsByTagName("td")[0];
    if (td) {
    if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
    tr[i].style.display = "";
   } else {
    tr[i].style.display = "none";
   }
  }
 }
}
</script>

Additionally, here is the blade section featuring the search bar and main group foreach loops:

<div class="uk-width-5-10">

        <div class="md-input-wrapper search-form">
            <form id="searchProducts">
                <input type="text" class="md-input label-fixed" name="srch-term" id="srch-term" autofocus placeholder="Search Products"/>
                <span class="md-input-bar"></span>

            </form>
        </div>

<?php
$tempdata = [];
$i = 0;
?>

@foreach ($orderFormData->pgroups as $pgroup)
        <h3 style="font-size: 26px; padding: 10px 0;">{{ $pgroup->group_name }} - {{ $pgroup->group_code }}</h3>
        <p class="uk-text-muted" style="font-size: 20px;" >{!! html_entity_decode($pgroup->group_desc) !!} <!--Group Description-->



            <div class="uk-width-8-10">
                <table class="uk-table" style="width: 100%; min-width: 768px;">
                    <thead>
                    <tr>
                        <th style="width: 10%; font-size: 20px;">Frame</th>
                        <th style="width: 20%; font-size: 20px;">Description</th>
                        <th style="width: 15%; font-size: 20px;">Cover/Color</th>
                        <th style="width: 15%; font-size: 20px;">Cover/Color</th>
                        <th style="width: 20%; font-size: 20px;">Quantity</th>
                        <th style="width: 15%; font-size: 20px; text-align: center;"><b>Price</b></th>
                    </tr>
                    </thead>

                    <tbody>

                    @foreach ($pgroup->pskus as $psku)
                    <?php $tempdata['sku-' . $i] = $psku ?>
                    <tr class="@if (isset($psku->quantity) && $psku->quantity > 0) {{ highlight }} @endif">
                        <td style="font-weight: 500; line-height: 30px; font-size: 14px;">{{ $psku->frame_fmt }}</td>
                        <td style="font-weight: 500; line-height: 30px; font-size: 14px;">{!! html_entity_decode($psku->frame_desc) !!}</td>
                        <td style="font-weight: 500; line-height: 30px; font-size: 14px;">{{ $psku->cover1_code }}/{{ $psku->color1_code }} {{ $psku->color1_desc }}</td> 
                        <td style="font-weight: 500; line-height: 30px; font-size: 14px;">{{ $psku->cover2_code }}/{{ $psku->color2_code }} {{ $psku->color2_desc }}</td>

                        <td style="font-weight: 700; line-height: 30px; font-size: 14px;">
                            <span style="text-align: center; display: block; width: 100%;">${{ $psku->price }}</span>
                        </td>
                    </tr>
                    @if ($psku->avail_date)
                    <tr>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td style="text-align: right; font-weight: 700;">Available Date:</td>
                        <td style="color: #ff0000;">{{ \Carbon\Carbon::createFromFormat('dmY', $psku->avail_date)->toDateString() }}

                    </tr>
                    <?php $i++; ?>
                    @endforeach
                    </tbody>
                </table>
            </div>

        </div>
@endforeach

I feel like my current approach with JS might be flawed, and I need guidance on initiating a suitable live filtering mechanism. I can experiment with different filtering methods once I understand how to begin. Any advice on implementing an effective JS live filter on this search bar/page setup would be highly appreciated.

Answer №1

Implementing this functionality is smoother when utilizing a front-end framework.

While it may not be the optimal approach, one potential solution could involve the following steps:

const searchInput = document.getElementById("search-input");
const tableRows = document.querySelectorAll('tbody');
searchInput.addEventListener("change", applyFilter);

function applyFilter(event) {
  const searchText = event.target.value;
  tableRows.innerHTML = ''; // Clear existing data from the view
  const filteredData = jsonData.records.filter(item => item.title === searchText); // Adjust this line based on your JSON structure
  let tableCells = [];
  filteredData.forEach(item => { 
    const cell = document.createElement('td');
    cell.textContent = item.name;
    tableCells.push(cell);  
  });
  tableRows.appendChild(tableCells);
}

Answer №2

Consider utilizing the dataTables.js plugin from jQuery, as it offers a user-friendly and convenient way to manage tables. It comes equipped with a built-in search bar that allows you to easily search for specific items within the table. Additionally, you can easily sort the table in ascending or descending order with this plugin.

Here are the CDN links for easy access:

CSS: //cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css

JS: //cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js

jQuery:

$(document).ready(function(){
        $('#myTable').DataTable();
    });

To implement this in your table, simply assign the ID #myTable.

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

Understanding Mongodb: the process of populating a schema that is referenced within another schema using an API

Looking to make adjustments to my Api in order to populate a referenced schema. Here's the schema I am working with: export const taskSchema = new Schema ({ user:{ type: String, required: true }, project: { type ...

How can you enhance functionality in Polymer without the need to create a custom element?

This is the code snippet from my index.html file in Polymer 1.1: <template is="dom-bind" id="app"> <paper-drawer-panel force-narrow id="the-drawer"> <paper-header-panel drawer> <paper-toolbar></paper-too ...

Converting C# data into XML format

I am currently working with data obtained from the web, which is structured as follows (in a stream): {"parts":[ {"title":"Heading1","logo":"http:\/\/asd.com\/3.png","date":{"d":"24","m":"01","y":"2012"}, "blocks":[ [ {"time":"01:23 ...

Applying background-image in ngStyle results in an undefined value

I have been attempting to incorporate images (retrieved through an API) as the background-image of an element. However, I keep encountering the error message Cannot read property 'url' of undefined, even though the URL is actually being rendered. ...

Exploring the process of handling and returning JSON-encoded form errors within Symfony

I am looking to develop a webservice where I can submit a form and receive a JSON encoded list specifying which field is incorrect in case of errors. Currently, I am receiving a general list of error messages without specific identification of the fields ...

AngularJS: Using $watch to retrieve the index of the modified item within an array

My current situation involves an array containing multiple objects. $scope.userCompetences = []; To monitor any changes in this array, I have implemented a deep watch: $scope.$watch('userCompetences', function (newVal, oldValue) { ...

Leveraging database functionality through sequelize

I'm a beginner in Express and I want to learn how to create a "Select *" query on a table. I know that I need to create a model of the table in a .js file and I have a good understanding of the next steps. However, my question is: How can I create a ...

What is the best way to iterate through JavaScript objects within a Jade template?

Technologies such as Node.js, Jade, socket.io, jQuery, and JSON are being used in my project. In my "index.jade" file, I have the following code that receives "results" data as JSON from the backend: extends layout block content ul // more jade html h ...

How can I correctly update values from a sibling component that has been imported in Vue.js 2.0?

My Vue 2.0 project follows the single-file component approach and consists of three components: App (parent), AppHeader, and FormModal. Both AppHeader and FormModal are direct children of App and siblings of each other. The main objective is to toggle the ...

Retrieving specific data from JSON by utilizing JSONPath, while omitting certain values

I have a JSON data set structured like this: [ { "accID": "3asdasd321asdasdfsadf2", "test": "one", "isGood": "true", }, { "accID": "Not Found", "test": "two", "isGood": "true", }, { "accID": "1asdasd121asdasdfsadf5", "test": "five", "isGood": "false", } ] ...

Unveiling the mystery: Locating the position of an element within a multidimensional array using JavaScript or JQuery

How can I retrieve the index of a specific element in a JSON array converted from a PHP array using json_encode, using JavaScript or JQuery? Initially, the user will choose an option where the values correspond to people's IDs. <select class="for ...

Discovering elements using Selenium in a JavaScript popup box

The issue at hand is rather straightforward. I am faced with the task of clicking on an element within a popup that has been dynamically generated by JavaScript code. The challenge arises as the page is solely accessible in Internet Explorer and the elemen ...

Sending a sound recording to the express js server with the help of multer

I'm currently working on a project where I need to record audio and save it in my local directory (uploads folder) using express js and multer. The recording part is working fine with mic-recorder-to-mp3, but I'm facing an issue with saving the r ...

The property being set in Angular is undefined, causing an error

I am struggling to understand why the code below is not functioning as intended: Main.html <div class="MainCtrl"> <h1>{{message.test}}</h1> </div> Main.js angular.module('myApp') .controller('MainCtrl', f ...

Utilize jq to Transform JSON File into CSV Format

I've been utilizing curl to retrieve Alien Vault OTX pulses from their API. Once I receive the initial output in json format, my goal is to convert it into csv using jq for compatibility with other software. Many have recommended jq for this purpose, ...

Exploring the Unpredictable Results of Recursive Functions in JavaScript

Take a look at this recursive code snippet. function calculateFactorial(n) { if (n === 0 || n === 1) { return 1; } else { console.log(calculateFactorial( (n - 1) )); return n * calculateFactorial(n - 1); } } const num = ...

Creating a function to manipulate an element on a different webpage

Upon clicking a button on Page1, a function is triggered which then calls another function to generate HTML and append it to a div with the #lista id. The issue here is that #lista belongs to Page2, so I am unsure if there is a syntax similar to ajax where ...

Activate a button upon the user clicking the Enter key

Is there a way to automatically trigger a button click when the user presses the Enter key inside an input field? I've attempted to achieve this functionality, but have been unsuccessful so far. Here is my code snippet: <!DOCTYPE htm ...

Revamp the Vue component for better DRYness

Seeking advice on a more efficient way to improve the code below and make it DRY: <h2>{{ title }}</h2> <p>{{ subtitle }}</p> I am currently checking this.name for both the title and subtitle, wondering if there is a better implemen ...

Iterating over a range of values with _.each()

Can someone help me figure out why my syntax is incorrect for applying two values from different iteratees (day.classes and event.part) on line 5? <div class="days"> <div class="headers"> <% _.each(daysOfTheWeek, function(day) { %&g ...