Implementing JavaScript to display specific content when a list is devoid of any items

Currently, I am in the process of developing a basic contact list web application where the contacts are listed within li elements. My aim is to adjust the visibility of the text in the p#no-contacts element based on whether the containing ul has any children or not. Ideally, when the ul contains 0 children, the text should have a display: block property, and if it contains one or more children, then the text should have a display: none property. However, despite my efforts, this functionality doesn't seem to be working.

Please find the JSFiddle for reference - https://jsfiddle.net/stqyujhw/

The issue seems to lie around Line 94 in the JavaScript section:

if (contactList.children.length < 1) {
    noContactsMessage.style.display = "block";
} else if (contactList.children.length >= 1) {
    noContactsMessage.style.display = "none";
}

I am quite perplexed by what could be causing the problem. As I am still relatively new to JavaScript, any advice or guidance on troubleshooting this would be greatly appreciated. Thank you in advance.

Answer №1

After reviewing the fiddle link provided in the question

This specific piece of code needs to be included in both the delete and add contact event handlers. For example, the deleteContact function should contain the following statement:

 function deleteContact(e) {
    if (e.target.classList.contains("delete")) {
        if (confirm("Are you sure?")) {
            e.target.parentElement.remove();
        }
    } else if (e.target.classList.contains("fas")) {
        if (confirm("Are you sure?")) {
            e.target.parentElement.parentElement.remove();
        }
    }
    if (contactList.children.length < 1) {
       noContactsMessage.style.display = "block";
    }
// DISPLAY NO CONTACTS MESSAGE IF THERE ARE NO CONTACTS


}

Similarly, the add function should be structured as follows:

function addContact(e) {
    e.preventDefault();
    const nameValue = addForm.querySelector("#name-input").value;
    const numberValue = addForm.querySelector("#number-input").value;
    const li = document.createElement("li");

    const nameSpan = document.createElement("span");
    nameSpan.classList.add("name");
    nameSpan.textContent = nameValue;

    const numberSpan = document.createElement("span");
    numberSpan.classList.add("number");
    numberSpan.textContent = numberValue;

    const deleteButton = document.createElement("span");
    deleteButton.classList.add("delete");
    const delIcon = document.createElement("i");
    delIcon.className = "fas fa-user-minus";
    deleteButton.appendChild(delIcon);

    li.appendChild(nameSpan);
    li.appendChild(numberSpan);
    li.appendChild(deleteButton);
    contactList.appendChild(li);
    if (contactList.children.length >= 1) {
    noContactsMessage.style.display = "none";
 } 
}

Your code logic wasn't executing within the event handlers causing unexpected behavior.

Answer №2

The specified code does not run every time a li is deleted or added. Instead, it only runs once during the initial loading. To fix this, place the code in the event handler for the corresponding actions.

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

Utilizing a feature module imported from a separate Angular4 project

I have a question about setting up an Angular 4 project. Can feature modules be loaded from another Angular 4 project? I am currently attempting to maintain separate project repositories and dynamically load feature modules into the main project. This wa ...

Are there any JS/jQuery plugins available for sliding animations that include slideLeft and slideRight functions, similar to the slideUp and slideDown functions?

Does anyone know of a jQuery/JS plugin that combines fading and sliding effects, specifically with slideLeft and slideRight functions similar to jQuery's slideUp and slideDown? I'm hoping to find something ready-made rather than having to build i ...

JavaScript utilizing an API to retrieve specific data values

Below is some API Data that I have: [ { "symbol": "AAPL", "name": "Apple Inc.", "price": 144.98, "changesPercentage": -1.22, "change": -1.79, ...

Tabs within the AutoComplete popup in Material-UI

Would it be feasible to showcase the corresponding data in the AutoComplete popover using Tabs? There could be potentially up to three categories of data that match the input value, and my preference would be to present them as tabs. Is there a way to in ...

Here is the process to make a GET request to an API with input parameters using JQuery and JavaScript in an Asp.net view when a particular tag

Seeking assistance in displaying the count of orders on my view using a special tag. I have written a stored procedure in SQL that returns the order count based on the input type. To showcase all types of orders, I have designed multiple boxes on my form. ...

Does Google's web crawler have the ability to index content created by javascript?

Our web app generates content using javascript. Can Google index these pages? In our research on this issue, we primarily found solutions on older pages suggesting the use of "#!" in links. Within our app, the links are structured as follows: domain.co ...

Creating a grid UI in AngularJS using Typescript: utilizing functions as column values

I am working on an AngularJS app that includes the following UI grid: this.resultGrid = { enableRowSelection: true, enableRowHeaderSelection: false, enableHorizontalScrollbar: 0, enableSorting: true, columnDefs: [ { name: &apos ...

Attempting to conceal the API, however, the backend is throwing an error

view the error image I am currently in the process of developing an NFT search application that is capable of locating the NFTs associated with a specific wallet address. However, I am faced with the challenge of using Alchemy without exposing the API key ...

The Shopify storefront API's create cart mutation generates an HTML response when called

I recently started developing an e-commerce website using Next.js and Shopify's storefront API. I have successfully set up the connection and can list all the products from the API. However, I encountered an issue when attempting to add a product for ...

When implementing jQuery for scrolling on a website, touch gestures may become unresponsive on Safari for iOS devices

While developing a custom website with Angular, I encountered an issue specifically with Safari on iOS. The website is a single-page app with multiple menu sections that trigger a scroll animation when selected using jQuery. Everything was working smoothly ...

Encountering a CORS policy issue while attempting to retrieve data from an API

I have been attempting to retrieve data from the DHL API, however, I keep encountering issues due to CORS policy blocking the request. Even though I have configured the CORS policy on my backend server, the error persists. What could be the issue? Here ...

Javascript Select Element with No Options

I'm currently working on a <select> element that is being populated from an array using the following code snippet: <select id="selector" name="selector"</select> <button type=button onclick=populateSelect(states)>Click me1!</ ...

Is there a way to handle button click event when utilizing this.props.children in React?

I have recently completed a React component that serves as a modal wrapper. The content for this modal is passed through the props.children property. Inside the content, there is a button that, when clicked, should trigger an event in the parent component. ...

"Utilize Ajax to trigger a custom alert message once data is loaded and ready

Is it possible to customize the data object in order to show a JavaScript alert saying "The email address has already been registered!"? Currently, the servlet returns a boolean indicating whether the email is already in the database. $('#emailInput ...

Simplified jQuery function for multiple div mouseover operations

Uncertain about the accuracy of my title. Due to certain reasons, I need to assign different IDs for the class, as it only detects ID and not class when hovered over. Therefore, I have created a CSS version where the opacity of a specific div will change t ...

Is it possible to pre-select a value in a PrimeVue Dropdown component?

Situation: Currently, I am incorporating PrimeVue into a Vue.js project. Within this setup, there is a dropdown component sourced from PrimeVue, utilizing an array of objects. The structure of the dropdown component appears as follows: <template #positi ...

Google Chrome's development tools are unable to detect the manifest

I have a file named manifest.json, and I included it in my HTML using <link rel="manifest" href="./manifest.json">. Despite everything seeming correct, Chrome developer tools are unable to detect my manifest file! This is the content of my manifest ...

Changing the data of a child component that is passed through slots from a parent component in Vue.js

Exploring the world of components is new to me, and I'm currently trying to understand how the parent-child relationship works in components. I have come across component libraries that define parent-child components, such as tables and table rows: &l ...

"The Django querydict receives extra empty brackets '[]' when using jQuery ajax post to append items to a list in the app

Currently, I am tackling a project in Django where I am utilizing Jquery's ajax method to send a post request. The csrftoken is obtained from the browser's cookie using JavaScript. $.ajax({ type : 'POST', beforeSend: funct ...

Issue with JQuery: Inability to deactivate an element after receiving an Ajax response

My dynamic dialogue box, generated via Ajax return, presents a challenge involving the dynamically changing drop-down list element $('#functionSelect'). I require this list to trigger disabling of input fields within the dialogue box upon changes ...