Enhancing User Experience with Search Functionality in JavaScript

 In continuation with previous article on how to fetch data from an API and display it in tabular form, we will further enhance the demo application by adding search functionality to search through the content displayed in the table.

Adding a search feature to any web application significantly improves user experience by allowing users to quickly filter and find relevant data. In this blog post, we'll discuss how a real-time search functionality was implemented using JavaScript in a web page that fetches and displays user data from an API.

The JavaScript code fetches user data from the JSONPlaceholder API, displays it in a table, and enables users to search dynamically through the data by name or email.

  1. In the html file, create a input field by enter below code where you can enter the text that you want to search in table.
<input class="input input-bordered input-primary w-full max-w-xs" type="text" id='search' placeholder='Enter text to search...' />

When the user clicks the "Load Data" button (submitdata), the fetchData() function is triggered. This function:

function fetchData() {
    console.log('data is fetching');
    const apiUrl = 'https://jsonplaceholder.typicode.com/users';
    fetch(apiUrl)
    .then(response => response.json())
    .then(data => {
        globalData = data;
        displayDataInTable(globalData);
    })
    .catch(err => console.error('error fetching data..', err));
}


Key Takeaway: Storing fetched data in globalData allows us to use it for searching without making multiple API calls.

Once the data is fetched, it is displayed inside a <table> by dynamically creating rows and inserting the user information.

function displayDataInTable(data) {

    const tbod = document.querySelector('#datatable tbody');

    tbod.innerHTML = ''; // Clear previous data before inserting new rows


    data.forEach(user => {

        const row = document.createElement('tr');


        const id = document.createElement('td');

        id.textContent = user.id;

        row.appendChild(id);


        const name = document.createElement('td');

        name.textContent = user.name;

        row.appendChild(name);


        const email = document.createElement('td');

        email.textContent = user.email;

        row.appendChild(email);


        tbod.appendChild(row);

    });

}

Key Takeaway: The function dynamically updates the table by clearing existing rows and adding new rows for each user.

The search functionality listens for user input (input event on the search field) and dynamically filters the displayed data.

searchData.addEventListener('input', function(event) {

    event.preventDefault();

    const searchValue = searchData.value.toLowerCase();

    console.log(searchValue);


    // Filter users based on search input (by name or email)

    const filteredData = globalData.filter(user =>

        user.name.toLowerCase().includes(searchValue) ||

        user.email.toLowerCase().includes(searchValue)

    );


    console.log("filtered data", filteredData);

    displayDataInTable(filteredData);

});

Key Takeaway:

  • The search is case-insensitive (using toLowerCase()).

  • It searches through both name and email fields.

  • As the user types, the table updates in real time without requiring additional API calls.

Adding a search feature enhances usability by allowing users to quickly find relevant information without scrolling through large datasets. This JavaScript-based search implementation provides an efficient, real-time filtering experience, making it a valuable addition to any data-driven web application.

Post a Comment

0 Comments