Is it possible to alter HTML content dynamically by searching with JavaScript?

When I utilize a search function to find contact information for individuals, initially there are four contacts listed:

1)

"Jonathan Buell", 5804337551, "family"

2)

"Patrick Daniel", 8186934432, "work"

3)

"Lorraine Winter", 3138211928, "work"

4)

"Constance Reed", 3138211928, "family"

For example, if I type j in the input box, only Jonathan Buell should be displayed. Similarly, typing Lorr should show details for Lorraine Winter. If the string does not match any contact, such as when the user types xyz, no contact should be displayed.

Despite attempting to implement this search feature, the content does not update dynamically and no changes are visible.

Index.html:

var array = [];

function Person(fullName, number, group) {
  this.fullName = fullName;
  this.number = number;
  this.group = group;
  array.push(this);
}

var p1 = new Person("Jonathan Buell", 5804337551, "family");
var p2 = new Person("Patrick Daniel", 8186934432, "work");
var p3 = new Person("Lorraine Winter", 3138211928, "work");
var p4 = new Person("Constance Reed", 3138211928, "family");

console.log(array);

function showContacts() {
  for (var i in array) {
    var id = i;
    contactlist.innerHTML +=
      `
            <ul>
            <div>
            <p>Name: ` + array[i].fullName + `</p>
            <p>Number: ` + array[i].number + `</p>
            <p>Group: ` + array[i].group + `</p>
            <button type="button" class="btn btn-warning" onclick="editContact(` + id + `)">Edit</button>
            <button type="button" class="btn btn-danger">Delete</button>
            </div>
            `
  }
}

showContacts();

function search() {
  var search = document.getElementById("search").value;

  contactlist.innerHTML = '';

  for (var i in array) {
    if (array[i].fullName.toLowerCase().includes(search.toLowerCase())) {
      var id = i;
      contactlist.innerHTML =
        `
            <ul>
            <div>
            <p>Name: ` + array[i].fullName + `</p>
            <p>Number: ` + array[i].number + `</p>
            <p>Group: ` + array[i].group + `</p>
            <button type="button" class="btn btn-warning" onclick="editContact(` + id + `)">Edit</button>
            <button type="button" class="btn btn-danger">Delete</button>
            </div>
            </ul>
            `;
    }
  }
}
<!DOCTYPE html>
<html>

<head>
  <title></title>
</head>

<body>

  <div class="input-group">
    <input type="text" id="search" class="form-control" placeholder="Search">
  </div>
  </form>
  </div>

  <div id="contactlist">

  </div>


  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

</body>

</html>

Here is a screenshot of my application :

https://i.sstatic.net/IoxlW.png

Answer №1

Here is a simple solution that works well with jQuery:

$(".search").on("input",function(){

        // Retrieve the input field text and reset the count to zero
        var filter = $(this).val(), count = 0;

        // Loop through the comment list
        $("#contactlist .main_div").each(function(){

            // If the list item does not contain the text phrase fade it out
            if ($(this).text().search(new RegExp(filter, "i")) < 0) {
                $(this).fadeOut();

                // Show the list item if the phrase matches and increase the count by 1
            } else {
                $(this).show();
                count++;
            }
        });
    });

Another tip is to give a class to the parent div when adding divs like below:

for (var i in array) {
    if (array[i].fullName.toLowerCase().includes(search.toLowerCase())) {
      var id = i;
      contactlist.innerHTML =
        `
                        <ul>
                        <div class="main_div">
                        <p>Name: ` + array[i].fullName + `</p>
                        <p>Number: ` + array[i].number + `</p>
                        <p>Group: ` + array[i].group + `</p>
                        <button type="button" class="btn btn-warning" onclick="editContact(` + id + `)">Edit</button>
                        <button type="button" class="btn btn-danger">Delete</button>
                        </div>
                        </ul>
                        `;
    }
  }
}

Answer №2

Alone, your search input doesn't have any knowledge of the JavaScript array or its contents. The search() function is not triggered; simply assigning an id of "search" to your input does not link it to the function.

However, you can set up an event listener on your search input to detect the enter key being pressed. Once that happens, your array of people can then be filtered accordingly.

You could implement something similar to this:

// Since you imported jQuery, you might as well use $("#search") instead of document.getElementById("search)
var search_input = $('#search')

search_input.keydown(function (event) {
    if (event.which === 13) {
        // If the enter key was pressed
        search()
    }
})

function search(event) {
    event.preventDefault();

    var search_val = search_input.val();

    contactlist.innerHTML = '';

    for(var i in array) {
        if (array[i].fullName.toLowerCase().includes(search_val.toLowerCase())) {
            var id = i;
            contactlist.innerHTML = `
                <ul>
                    <div>
                        <p>Name: `+ array[i].fullName +`</p>
                        <p>Number: `+ array[i].number +`</p>
                        <p>Group: `+ array[i].group +`</p>
                        <button type="button" class="btn btn-warning" onclick="editContact(`+ id +`)">Edit</button>
                        <button type="button" class="btn btn-danger">Delete</button>
                    </div>
                </ul>
            `;
        }
    }
}

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

Determine if the start_date is greater than the end_date using jQuery

Having a particular issue with date validation. The start_date and end_date are obtained from an HTML form, being chosen using a bootstrap date picker. A sample of the dates looks like this: start_date = 15-06-2016 end_date = 14-06-2016 To verify if th ...

Strategies for Emphasizing Individual Content Links on a Single-Page Website with Dynamic Content Replacements

My website consists of a single page with content that gets replaced using jQuery when the menu is clicked. Even though the links do not lead to different pages, just different divs, I want the menu to behave like a typical website menu with three states: ...

Showing pictures from a JSON source

I am currently facing an issue while trying to display the cover art along with the search results. There seems to be a problem in the img src tag that is preventing the app from loading properly. Interestingly, when I direct the img to data.tracks[i].albu ...

Unique Scrollbar Design for Chrome Extensions

While working on my website, I decided to incorporate a custom scroll bar using a script called fleXcroll. However, I noticed that when clicking inside the scrollable content, a large yellow border appears around the wrapper. This is puzzling because this ...

Cookies are failing to be saved upon reloading the page

I found this snippet of code $(document).ready(function () { var d = new Date(); var newMinutes = d.getTimezoneOffset(); var storedMinutes = getCookieValue("tzom"); if (newMinutes != storedMinutes) { setCookie("tzom", newMinutes) ...

What steps should I take to fix the error that arises when I am using the mysql module?

When attempting to connect my local database using the node module, I encountered the following error message: Client does not support authentication protocol requested by server; consider upgrading MySQL client next is my configuration: const mysql = r ...

The issue of background and footer distortion arises in PhoneGap when the keyboard is opened

Currently, I am experiencing screen problems with phonegap. The issue arises when a keyboard is opened, causing the back button at the bottom of the page to move above the keyboard and resulting in the background image appearing shorter. How can this be re ...

my divs are not being affected by the max-width property and are retaining their

I've been learning CSS and HTML through an interesting tutorial on Udacity. Here's the code I've been working on: .image{ max-width: 50%; } .app{ display: flex; } .description{ color: red; max-width: 705px; } <h1 class="title" ...

Overlaying div above vimeo player

I'm attempting to overlay a div on top of a Vimeo video, a task I anticipated would be straightforward but turns out to be more complex than expected. Below is the HTML code snippet: <div id="wrap"> <iframe id="video" s ...

Shifting an html element from side to side using javascript click event

I am new to utilizing JavaScript in conjunction with HTML elements, and I am seeking assistance in crafting a function for such interaction. The goal is to have an image that will shift either left or right based on its previous movement. For instance, up ...

What could be the reason that my Bootstrap dropdown menu is not appearing on my website

I am currently utilizing Angular in my project. I have incorporated bootstrap and jQuery via NPM install, and specified them as dependencies in angular.json. The navbar on my site contains a dropdown menu. When I hover over the dropdown menu, it should di ...

Solving compatibility problems with jquery AJAX requests on multiple browsers

searchCompanyExecutives: function(criteria, callback) { var params = $j.extend({ type: "GET", data: criteria, url: "/wa/rs/company_executives?random=" + Math.floor(Math.random() * (new Date()).getTime() + 1), ...

The printed PDF of a webpage does not display HTML table background colors in Chrome or Firefox

Is there a way to change the colors of table cells in an HTML table when exporting to PDF? I'm creating content dynamically that includes background-color: #ffffff (or red) and showing it on a webpage, but the cell backgrounds appear as white in the P ...

What is the method for adjusting the input text color in a textarea to green?

Is there a way to change the input color for this textarea so I can type green text on a black background? textarea{ background-color: black; } <textarea id="htmlCode" class="1111" placeholder="HTML"></textarea> ...

Personalize scrollbar appearance in Mozilla Firefox and Internet Explorer

When it comes to customizing the scrollbar in chrome, CSS makes it easy: ::-webkit-scrollbar { width: 7px; } Unfortunately, this method does not have the same result in Firefox (version 38) and IE (version 11). I attempted the following code as an alter ...

The datepicker view is obscured by the div layer

When it comes to displaying datepickers in table rows, there seems to be a discrepancy. The datepickers in the top rows are functioning correctly, as shown in the first image. However, the datepickers in the bottom rows are not displaying properly, as illu ...

The application of texture to a sphere in Next.js with Three.js seems to be malfunctioning

Hi there, I'm having some trouble getting a texture to apply correctly to a sphere within a Next.js component. I've attempted it with the code provided below, but all I see is a black ball rendering instead. I suspect it might have something to ...

Retrieving an attribute through the act of clicking a button

How can I retrieve the rel attribute value when clicking on a button with the class selector? <button class="nameClass" rel="relName">Content</button> I am attempting to achieve this by: $(".nameClass").click(function(){ // Here is where ...

Guide to testing Vuex Mutations with Vue-test-utils and Jest

I have reviewed a few tutorials on mocking and testing Vuex actions, but I have struggled to implement them successfully on my own. Despite following the steps outlined in the links provided, I consistently encountered an issue where toHaveBeenCalled would ...

I have noticed that there are 3 images following the same logical sequence, however only the first 2 images seem to be functioning correctly. Can you help

Update: I have found a solution that works. You can check it out here: https://codepen.io/kristianBan/pen/RwNdRMO I have a scenario with 3 images where clicking on one should give it a red outline while removing any outline from the other two. The first t ...