Is there a way to show the same array with added and removed items without the need for a separate page or refreshing in vanilla JS and HTML?

Seeking help for my mini CRUD project created using vanilla JS and HTML. The main challenge is to dynamically add or remove items from an array of movies and display the updated list without refreshing the page since the movie data is hard-coded.

The issue arises when trying to prevent duplicate arrays from being displayed on the page each time a title is added or removed.

If anyone has a solution to this problem, it would be greatly appreciated!

Below is a snippet of the current code:

window.onload = function () {

  //Hard-coded array of movies - data.
  // No database connection so array resets on page refresh. 
  var movies = [
    'The Shawshank Redemption', 'The Godfather', 'Star Wars: Episode V - The Empire Strikes Back',
    'Forrest Gump', 'The Perks of Being a Wallflower', 'The Dark Knight', 'Changeling', 'It\'s a Wonderful Life',
    'The Silence of the Lambs', '8 Mile', 'The Breakfast Club', 'Django Unchained', 'Silver Linings Playbook',
    'The Shining', 'Seven', 'American Beauty', 'Pulp Fiction', 'Zero Dark Thirty', 'Argo', 'The Hurt Locker'
  ];

  // DOM manipulation variables
  // var movieList = document.getElementById("movie-list__container");
  var videoInput = document.getElementById("videoInput");
  var addVideo = document.getElementById("addVideo");
  var removeVideo = document.getElementById("removeVideo");
  var alertMsg = document.getElementById("alertMsg");
  var autocomplete = document.getElementById("autocomplete");
  var searchResults = document.getElementById("search-results");
  var movieListResults = document.getElementById("movie-list-results");

  listMovies();

  function listMovies() {
    movies.sort();
    for (i = 0; i < movies.length; i++) {
      movieListResults.innerHTML += "<li>" + movies[i] + "</li>"
    };
  }

  addVideo.onclick = addMovies;

  function addMovies() {
    var title = videoInput.value;
    if (add(movies, title)) {
      videoInput.value = "";
      searchResults.innerHTML = '';
      movieListResults.innerHTML += "<li>" + title + "</li>";
      alertMsg.classList.remove("fail");
      alertMsg.classList.add("success");
      alertMsg.innerHTML = "Title was inserted successfully";
    } else {
      alertMsg.innerText = 'Please add a video title';
      alertMsg.classList.remove("success");
      alertMsg.classList.add("fail");
    }
  }

  function add(data, title) {
    if (title == "") {
      return false;
    } else {
      data.push(title);
      return true;
    }
  }

  autocomplete.onkeyup = function () {
    var results = [];
    var userInput = this.value;
    searchResults.innerHTML = "";

    if (userInput != "") {
      results = search(movies, userInput);
      searchResults.style.display = "block";

      if (results.length == 0) {
        searchResults.innerHTML += "<li>Not found</li>";
        searchResults.style.color = "grey";
      } else {
        searchResults.style.color = "black";
        for (i = 0; i < results.length; i++) {
          searchResults.innerHTML += "<li>" + results[i] + "</li>";
        }
      }
    }
  };

  function search(data, input) {
    var results = [];
    for (i = 0; i < data.length; i++) {
      if (input.toLowerCase() === data[i].slice(0, input.length).toLowerCase()) {
        results.push(data[i]);
      }
    }
    return results;
  }

  removeVideo.onclick = deleteMovie;

  function deleteMovie() {
    var title = videoInput.value;
    if (title === "") {
      alertMsg.innerHTML = 'Please enter the title you want to remove';
      alertMsg.classList.add("fail");
    } else {
      if (remove(movies, title)) {
        alertMsg.innerHTML = "Title has been successfully removed";
        alertMsg.classList.add("success");
      } else {
        alertMsg.innerHTML = "Title not found";
        alertMsg.classList.add("fail");
      }
    }
  }

  function remove(data, title) {
    for (var i = 0; i < data.length; i++) {
      if (title.toLowerCase() === data[i].toLowerCase()) {
        data.splice(i, 1);
        return true;
      }
    }
    return false;
  }

}; //End of window.onload

Answer №1

Update: I managed to solve the issue by removing the listMovies() function and simply printing the array once.

Subsequently, I implemented a for loop for addMovie() and deleteMovie() functions to iterate through the array and display it after making updates.

I discovered that all I needed to do was loop through the movies array and show the array again for both addMovie() and deleteMovie().

  for (i = 0; i < movies.length; i++) {
    movieListResults.innerHTML += "<li>" + movies[i] + "</li>"
  };

While my logic for adding and removing movie titles in JavaScript was correct, there was an issue with displaying the titles in HTML.

PS: Just so you know, I'm still a novice at this!

Cheers

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

Version 13 of the Discord slash command encounters an "interaction failed" error

After implementing the slash commands in Discord v13 as per the instructions on discordjs.guide, I encountered an issue when trying to use the commands - interaction failed. Here is a snippet of my code: // Here goes the code const { Client, Collection, ...

Utilizing Sinon.js in Node.js to conduct unit tests on Postgres interactions

I am struggling to figure out how to use sinon to mock a call to postgres that is required by the module I am testing. I'm not sure if it's even possible. I'm not trying to test the postgres module itself, just my object to ensure it's ...

Unable to locate property 'location' due to being undefined

When trying to use the react-router-dom 4.0.0 library, an error was encountered: Uncaught TypeError: Cannot read property 'location' of undefined The issue seems to be with browserHistory. Previously, I had been using react-router 2.x.x witho ...

Tips on creating an editable table row in Angular to easily update values

I'm currently developing an Angular application which is meant to extract data from an excel sheet and exhibit it in a table upon upload. I have incorporated an edit link beneath one column for the purpose of editing the row data; once you click on ed ...

Is it possible to have unique styles for individual tabs in a mat-tab-group using Angular Material?

Is it possible to have different text colors for each tab in a mat-tab-group and change the color of the blue outline at the bottom? If so, can you provide guidance on how to achieve this? Here is the default appearance of the tabs in my app: https://i.st ...

The graph created in an HTML format within an rmarkdown document appears too tiny when exported

Currently, I'm attempting to generate an HTML graph in a PDF output using rmarkdown: --- title: "Test report" output: pdf_document always_allow_html: yes params: plot: NA --- {r, echo=FALSE,message=FALSE, fig.height=4, fig.width=10, fig.show=&apo ...

What is the best way to position a button under an h3 heading using the display flex

Inside my div, I have an h3 and a button. The div uses display:flex; with justify-content:center; and align-items:center;. However, the button ends up sticking to the right side of the h3. I attempted placing the button in its own div, but this caused a la ...

Adding new elements to an array does not activate the reactivity of Vue

After discovering that editing objects within an array doesn't function properly in vue.js due to its limitations, I tried using vue.set to resolve the issue, but it's proving to be quite challenging for me. Let's take a look at the sample ...

Is the value of the index in the input constantly fluctuating in Vue?

I have a method that generates an array of objects in the following way: onCalculate_a(code) { let data = this.forms.calculate_a.map((p,i) => { return { product_code: code, price: p } }); this.su ...

The resize function fails to trigger when it is required

Struggling to get this code working properly. If the window width is greater than 800, I want 6 images with a red background. If the window width is less than 800, I want 4 images with a blue background. I need this functionality to work both on r ...

Enhancing Next.js SEO with 'use client' Metadata

Currently, I am facing an issue with my product page. The metadata for this page is fetched from the backend using an API that retrieves data from a database. To fetch this data and update it on the client side, I am utilizing a custom hook. However, the p ...

Is there a way to modify the visibility of an element on a webpage once an image element is clicked or activated?

I've been experimenting with changing the opacity of a div element when you click on an img element using JavaScript or jQuery. I'm not sure if this is achievable with CSS or HTML alone, so if you have any insights, please share! Here's the ...

The Openwave mobile browser is having trouble understanding CSS child selectors and descendant selectors

While testing my website on my LG VX8360 cell phone with Openwave Mobile Browser 6.2.3.2, I encountered a problem with CSS child selectors and descendant selectors. Despite specifying that only the second div should have a yellow background, both divs disp ...

Refresh the data using the Ajax function

I am attempting to implement a delete function using Ajax. function delCatItem(catitem){ var theitem = catitem; $.ajax({ url: "movie/deleteitem/", type: "POST", data: { "movieid" : catitem ...

Adjust the border colors of TinyMCE when it is in focus and when it is blurred

I'm currently working on a project using jQuery in conjunction with TinyMCE. I am focusing on changing the border colors when the TinyMCE editor is in focus, and then reverting them back to their original color on blur. Here's the snippet I&apos ...

Tips for implementing styling in a material table within a reactjs application

Is there a different way to set the display property to inline-block since cellStyle doesn't seem to recognize it? How can I adjust the width of a specific column, let's say with the name title, without affecting the width of all other co ...

Unable to activate the on('click') event when the button is loaded via AJAX

I am facing an issue with the on('click') event. I have a button that is loaded dynamically via ajax and has a click event attached to it. However, when I try clicking it, nothing happens even though the expected output should be showing an alert ...

I used npm to install AngularJS and then included AngularJS in my application

My goal is to set up AngularJS v1.5.x using npm and integrate it into my application for seamless utilization. Most tutorials opt for downloading the Angular Version from angularjs.org and manually adding it to the index.html within a <script></sc ...

Shining a component (or persona) however essentially duplicate a distinct term

Is it possible to highlight an element or word, but still copy a different word when hitting ctrl+c? For example, imagine I have an emoji represented by: Original text: :heart: Output in HTML: <span background={...logic here}></span> I am ...

Navigating through the DOM using JavaScript or regular expressions

I have a DOM string called innerHTML and I am looking to extract or display the node value using either JavaScript's DOM API or JavaScript RegEx. "<nobr> <label class="datatable-header-sortable-child" onmousedown="javascript:giveFeedback(&ap ...