In JavaScript, when the search input is empty, all items in the array are displayed

I want to ensure that if the input field is empty, no results are displayed. Currently, when you enter a name and then delete it, all the results in the array are shown.

const characters = [{
    first_name: "Abraham",
    last_name: "Lincoln",
    img: "https://upload.wikimedia.org/wikipedia/commons/a/ab/Abraham_Lincoln_O-77_matte_collodion_print.jpg"
  },
  {
    first_name: "Johnny",
    last_name: "Bravo",
    img: "https://ia.media-imdb.com/images/M/MV5BYTg4MDkwODgtYTBlNy00Yjc2LTg4NTYtZGE5YmFhYjY5NzU2XkEyXkFqcGdeQXVyNTM3MDMyMDQ@._V1_.jpg"
  },
  {
    first_name: "Barney",
    last_name: "Rubble",
    img: "https://upload.wikimedia.org/wikipedia/en/e/e2/Barney_Rubble.png"
  }
];

let searchInput = document.getElementById('searchInput');
searchInput.addEventListener('keyup', filterNames);

function filterNames() {
  let filterValue = document.getElementById('searchInput').value.toUpperCase();
  let output = '';

  for (let i = 0; i < characters.length; i++) {
    let firstName = characters[i].first_name.toUpperCase();
    if (firstName.indexOf(filterValue) > -1) {
      output +=
        '<div class="card">' +
        '<div class="img-container text-center">' +
        '<img src="' + characters[i].img + '" width=180 height=180 />' +
        '</div>' +
        '<div class="text-center">' +
        '<h5>' + characters[i].first_name + ' ' + characters[i].last_name + '</h5>' +
        '</div>' +
        '</div>';
    }
  }
  document.getElementById('characters').innerHTML = output
};
.card {
  display: inline-block;
  margin-right: 12px;
  float: left;
}
<div>
  <input type="text" id="searchInput" placeholder="Who do you seek?" />
</div>

<div id="characters"></div>

Check out the demo on jsfiddle

Your assistance is greatly appreciated.

Answer №1

You can implement validation using the following condition:

filterValue != ""

If the condition is true, you can modify the search results.

If the condition is false, you can clear the content.

I hope this information is helpful :)

const characters = [{
    first_name: "Abraham",
    last_name: "Lincoln",
    img: "https://upload.wikimedia.org/wikipedia/commons/a/ab/Abraham_Lincoln_O-77_matte_collodion_print.jpg"
  },
  {
    first_name: "Johnny",
    last_name: "Bravo",
    img: "https://ia.media-imdb.com/images/M/MV5BYTg4MDkwODgtYTBlNy00Yjc2LTg4NTYtZGE5YmFhYjY5NzU2XkEyXkFqcGdeQXVyNTM3MDMyMDQ@._V1_.jpg"
  },
  {
    first_name: "Barney",
    last_name: "Rubble",
    img: "https://upload.wikimedia.org/wikipedia/en/e/e2/Barney_Rubble.png"
  }
];

let searchInput = document.getElementById('searchInput');

searchInput.addEventListener('keyup', filterNames);

function filterNames() {
  let filterValue = document.getElementById('searchInput').value.toUpperCase();
  let output = '';

  if (filterValue != "") {
    for (let i = 0; i < characters.length; i++) {
      let firstName = characters[i].first_name.toUpperCase();
      if (firstName.indexOf(filterValue) > -1) {
        output +=
          '<div class="card">' +
          '<div class="img-container text-center">' +
          '<img src="' + characters[i].img + '" width=180 height=180 />' +
          '</div>' +
          '<div class="text-center">' +
          '<h5>' + characters[i].first_name + ' ' + characters[i].last_name + '</h5>' +
          '</div>' +
          '</div>';
      }
    }
    document.getElementById('characters').innerHTML = output
  } else {
    document.getElementById('characters').innerHTML = "";
  }

};
input {width:50%;margin-bottom:12px;}
.card {display:inline-block;margin-right:12px;float:left;}
.img-container {border:1px solid #000000;}
.text-center {text-align:center;}
<div>
  <input type="text" id="searchInput" placeholder="Who are you looking for?"/>
</div>

<div id="characters"></div>

Answer №2

The issue arises when the inner HTML is not being cleared if there is no input or if everything has been removed.

A simple solution would be to include the following snippet at the end of your code:

if(filterValue === ""){
    document.getElementById('characters').innerHTML = "";
}

Implementing this change should resolve the issue.

Answer №3

The issue lies in the fact that your search results need to be cleared out using a specific piece of code.

To solve this problem, simply wrap your clearing code with an if statement:

let searchInput = document.getElementById('searchInput');
searchInput.addEventListener('keyup', filterNames);

function filterNames() {
    let filterValue = document.getElementById('searchInput').value.toUpperCase();
    let output = '';

    if (filterValue) {
      for (let i = 0; i < characters.length; i++) {
          let firstName = characters[i].first_name.toUpperCase();

          if (firstName.indexOf(filterValue) > -1) {
              output +=
                  '<div class="card">' +
                  '<div class="img-container text-center">' +
                  '<img src="' + characters[i].img + '" width=180 height=180 />' +
                  '</div>' +
                  '<div class="text-center">' +
                  '<h5>' + characters[i].first_name + ' ' + characters[i].last_name + '</h5>' +
                  '</div>' +
                  '</div>';
          }
        }
    }

    document.getElementById('characters').innerHTML = output
};

By initializing your output variable as an empty string, when there's no filterValue, the empty string will replace the search results effectively.

Answer №4

The issue lies within this particular line of code:

if (firstName.indexOf(filterValue) > -1) {

When using the .indexOf() method to search for an empty string (""), it will return 0. As a result, the condition in the if statement will always evaluate to true, displaying all entries from the characters array.

To resolve this, you need to implement a "guard" to ensure that the for loop is only entered if the filterValue is not empty:

if (filterValue.length > 0) {
    for (let i = 0; i < characters.length; i++) {
        // ...
    }
}

const characters = [{
    first_name: "Abraham",
    last_name: "Lincoln",
    img: "https://upload.wikimedia.org/wikipedia/commons/a/ab/Abraham_Lincoln_O-77_matte_collodion_print.jpg"
  },
  {
    first_name: "Johnny",
    last_name: "Bravo",
    img: "https://ia.media-imdb.com/images/M/MV5BYTg4MDkwODgtYTBlNy00Yjc2LTg4NTYtZGE5YmFhYjY5NzU2XkEyXkFqcGdeQXVyNTM3MDMyMDQ@._V1_.jpg"
  },
  {
    first_name: "Barney",
    last_name: "Rubble",
    img: "https://upload.wikimedia.org/wikipedia/en/e/e2/Barney_Rubble.png"
  }
];

let searchInput = document.getElementById('searchInput');
searchInput.addEventListener('keyup', filterNames);

function filterNames() {
  let filterValue = document.getElementById('searchInput').value.toUpperCase();
  let output = '';

  if (filterValue.length > 0) {
    for (let i = 0; i < characters.length; i++) {
      let firstName = characters[i].first_name.toUpperCase();
      if (firstName.indexOf(filterValue) > -1) {
        output +=
          '<div class="card">' +
          '<div class="img-container text-center">' +
          '<img src="' + characters[i].img + '" width=180 height=180 />' +
          '</div>' +
          '<div class="text-center">' +
          '<h5>' + characters[i].first_name + ' ' + characters[i].last_name + '</h5>' +
          '</div>' +
          '</div>';
      }
    }
  }
  document.getElementById('characters').innerHTML = output
};
.card {
  display: inline-block;
  margin-right: 12px;
  float: left;
}
<div>
  <input type="text" id="searchInput" placeholder="Who are you searching for?" />
</div>

<div id="characters"></div>

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

After pressing the button to access the sidebar, all I see is a plain white screen

I've been diligently working on a school project, but I'm encountering some issues with the Sidebar button in the top left corner. Whenever I click on the button, it opens up to display a blank white page. Can anyone provide me with some assistan ...

Having trouble escaping single quotes in JSON.stringify when using a replacer function

I'm attempting to replace single quotation marks in the values of my JSON string with \' however, it seems to not be working when I try to use the replacer function. var myObj = { test: "'p'" } var re ...

Unable to access the POST value in the current context

I am having trouble retrieving the values from a simple form that consists of two files: APP.js and FORM.ejs. I am attempting to get the values submitted through the form. APP.js: const http = require('http'); const express = require("express"); ...

Step-by-step tutorial on designing an input slider to dynamically adjust the CSS :before linear-gradient values

Is there a way to achieve a gradient effect using pseudo-element :before on an image that can be customized by adjusting a slider input? I've been trying to implement this feature with the following code, but have not been successful so far. var ...

The Ajax call is being made twice

A code snippet using jQuery to send data is being executed twice with a single click, resulting in two HTTP requests both receiving a 200 response. $(function() { $('input[type=submit]').click(function() { $(this).unbind("click"); ...

Having trouble properly removing an item from an array using splice() function

I'm facing an issue with an array where I need to remove a specific object. I attempted using the splice() method, but upon implementation, it ends up removing all objects except the one that was found. Here's a snippet of my JavaScript code: On ...

Create a separate mongoose schema for every element in an array by utilizing ecmascript 6

After traversing an array, I create a new mongoose schema by adding two fields and then saving it. myArray.forEach(email => { const newUsers = new UserList({ email, uuid: uuidv4() }); newUsers.save().catch(err => console ...

AJAX parsing through JSON files generated by PHP

Need help with sending a json to an ajax call and reading it when it's sent. Plus, the json structure seems off due to the backslashes... This is the ajax function in question: function find(){ var type = $('#object_type').val( ...

The div element is supposed to only be visible when the user scrolls down and then back up, rather than when the

Looking for some help with a Javascript issue on my website (http://www.pjsmusic.com). I need a div of 200px to appear when the user scrolls down 40px. I have tried using the following Javascript code: $(document).scroll(function() { $('#jerkBox& ...

What is the best way to verify values in Vuejs based on their length?

<button type="submit" :disabled="(user.password && !$v.user.password.valid) || (user.confirmPassword && !$v.user.confirmPassword.sameAsPassword)">sda </button> By implementing a method based on character len ...

The dropdown menu in the navigation bar is overlapping with the datatable, creating a transparency effect

Working on a website layout that features a navbar at the top and a datatable below. However, when hovering over the navbar to reveal subitems, I notice a transparency issue where the navbar overlaps with the datatable. Below is a simplified version of my ...

Working with JSON data: including new child elements

Hey there, I'm just starting to work with JSON and TypeScript. I have a JSON object that needs processing, where each child value must be added up to set the parent values as the sum of corresponding attributes from its children. "parentValues":[{ ...

Using JavaScript to fetch HTML and apply CSS dynamically

Is there a way to retrieve all HTML within a div along with the corresponding CSS? A majority of the CSS is defined in classes within an external stylesheet. document.getElementById("mydiv") Currently, using the above code only fetches the HTML with inli ...

Exploring the parsing of jade forms using node.js

I need assistance on how to retrieve a user-selected item from a dropdown list in my jade code. Here is the snippet: extends layout block content p This is the CSV page p <select> <option value="domain">Domain</option> <o ...

Include a CSS counter style class that adds leading zeros

Looking for a way to increment a particular <p> style class (p.wp as an example) from 1 - n across multiple HTML pages. The challenge is that the number needs to have 4 digits, ranging from 0001 to 0117. #start_wp {counter-reset: WP 0;} p.wp{} p. ...

Exploring the variations in method declarations within Vue.js

Today, while working with Vue, I came across an interesting observation. When initially using Vue, there were two common ways to define a method: methods: { foo: () => { //perform some action } } and methods: { foo() { / ...

Angular 6: Utilizing async/await to access and manipulate specific variables within the application

Within my Angular 6 application, I am facing an issue with a variable named "permittedPefs" that is assigned a value after an asynchronous HTTP call. @Injectable() export class FeaturesLoadPermissionsService { permittedPefs = []; constructor() { ...

Mongoose Error: The function 'mongooseSchemahere' is not recognized as a valid function

Here is the mongoose Schema setup in models/user.js: const mongoose = require('mongoose'); const userSchema = mongoose.Schema({ loginId: String, firstname: String, lastname: String, eMail: String, password: String, acti ...

What is the best way to target and manipulate the transform property of multiple div elements in JavaScript?

Looking at this code snippet, my goal is to have all the boxes rotate 180deg with a single click, without needing to apply different ID names: function rotateAllBoxes() { var boxes = document.getElementsByClassName("box"); for (var i = 0; i < box ...

Display database information in a multidimensional array using PHP and MySQL

I'm struggling with organizing some data into a multidimensional array. Can someone help me convert and view the array like this? Thank you. Array (A => array (part_no=>A, control_no=>0001, qty=>1000)) Here is what I have attempted so fa ...