Remove a certain element from an array using innerHTML in JavaScript

I'm working on a simple project in JavaScript where I need to create a library with JavaScript objects and allow users to add new books. I have set up a form in HTML to collect user data and created new objects that are stored in an array called "library." The books are displaying correctly in the DOM, but now I'm facing an issue with deleting specific books. I have added a button for deleting books, but it only deletes the first book in the array. Any help would be greatly appreciated.

Here is the HTML:

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="./styles.css" />
    <title>Document</title>
</head>
<body>
    <h1>My Library</h1>
    <input id="title" type="text" placeholder="Book Title">
    <input id="author" type="text" placeholder="Book Author">
    <input id="date" type="text" placeholder="Publish Date">

    <select id="read" name="read">
      <option value="yes">yes</option>
      <option value="no">no</option>
    </select> 

    <input type="button" value="New Book" onclick="add_book()">

    <div id="display"></div>
  
    <script src="app.js"></script>
</body>
</html>


------------------------------------------------------------------------------------------------


JavaScript:

var library = [];

var title_input = document.getElementById("title");
var author_input = document.getElementById("author");
var date_input = document.getElementById("date");
var read_input = document.getElementById("read");

function Book(title, author, date, read) {
    this.title = title;
    this.author = author;
    this.date = date
    this.read = read
};

function add_book() {
    var newBook = new Book(title_input, author_input, date_input, read_input)
    library.push(`Title: ${newBook.title.value} <br>`+`Author: ${newBook.author.value} <br>`+
    `Release date: ${newBook.date.value} <br>`+`Read: ${newBook.read.value} <br>` )
    show_library(); 
};

function delete_book(arr, elem){
    index = arr.indexOf(elem);
    arr.splice(elem,1);
    show_library(); 
}

function show_library() {
    document.getElementById("display").innerHTML = "";
    for(i = 0; i<library.length; i++){
        document.getElementById("display").innerHTML += library[i]+
        '<button onclick="delete_book(library, library[i]);">Delete</button><br>';
    }
};

Answer №1

It seems like you have included library[i] as regular text in the DOM, which does not actually reference the variable i from your loop.

An alternative approach would be to pass the index as an argument and directly use it in your function delete_book.

var library = [];

var title_input = document.getElementById("title");
var author_input = document.getElementById("author");
var date_input = document.getElementById("date");
var read_input = document.getElementById("read");

function Book(title, author, date, read) {
    this.title = title;
    this.author = author;
    this.date = date
    this.read = read
};

function add_book() {
    var newBook = new Book(title_input, author_input, date_input, read_input)
    library.push(`Title: ${newBook.title.value} <br>`+`Author: ${newBook.author.value} <br>`+
    `Realease date: ${newBook.date.value} <br>`+`Readed: ${newBook.read.value} <br>` )
    show_library(); 
};

function delete_book(arr, index){
    arr.splice(index, 1);
    show_library(); 
}

function show_library() {
    document.getElementById("display").innerHTML = "";
    for(i = 0; i<library.length; i++){
        document.getElementById("display").innerHTML += library[i]+
        `<button onclick="delete_book(library, ${i});">Delete</button><br>`;
    }
};
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="./styles.css" />
    <title>Document</title>
</head>
<body>
    <h1>My Library</h1>
    <input id="title" type="text" placeholder="Book Title">
    <input id="author" type="text" placeholder="Book Author">
    <input id="date" type="text" placeholder="Publish Date">

    <select id="read" name="read">
      <option value="yes">yes</option>
      <option value="no">no</option>
    </select> 

    <input type="button" value="New Book" onclick="add_book()">

    <div id="display"></div>
  
    <script src="app.js"></script>
</body>
</html>

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

Should I utilize Sockets or Ajax for my project?

My Login Script Journey I have a goal in mind - to create a login script using Nodejs. I am currently exploring the options of utilizing sockets or ajax posts for this task. My Progress So Far I have Nodejs installed and have referenced this code in my ...

Execute a self-invoking JavaScript function with dynamic code

I'm facing a challenging problem that I just can't seem to solve... There's a function on another website that I need to use, but unfortunately, I can't modify it The code in question is: Now, I am looking to add a prototype "aaa" to ...

How can I retrieve an item from a JSON array if it is not an array in ASP.NET?

Is there a way to extract the Label, AskPrice, and LastPrice from the JSON data retrieved through the Cryptopia API? The JSON response contains multiple records, and I need to loop through them which requires converting them into an array. However, I enc ...

A guide on understanding tab-formatted text in a textarea using JavaScript (Vuejs)

Trying to decipher a text that has been copied into a Word table, the formatting is very confusing. I am looking to extract the rows as objects in an array, with the columns serving as properties of each object. I would like to accomplish this using Vuejs ...

Prevent anchor tags from modifying the current URL

In the realm of React, I am endeavoring to incorporate an anchor tag that directs users to an external website "https://www.google.com/". Within my code, there exist two instances of this very anchor tag. The initial tag functions as intended, effortless ...

Activate datepicker upon choosing a symbol

If the symbol field is selected, the datepicker is enabled. If the symbol field is not selected, the datepicker remains disabled. <script src="{{asset('js/libs/jquery.js')}}" crossorigin="anonymous"></script> <link href="https:/ ...

Using the `this` pointer in the fs.readFile function in Node.js

I want to load a list of objects from a file using the fs.readFile method with the use of the this keyword in my JavaScript class var MyReaderClass = (function() { //Const function MyReaderClass() { this.readObjects = []; /** ...

Utilizing Angular to Bind Data Visualization Charts Locally

I am attempting to use the Kendo UI Angular directives to bind a DataViz pie chart locally, but I am encountering an error that says: TypeError: Cannot call method 'toLowerCase' of undefined at h (http://localhost:51717/Scripts/kendo/kendo.d ...

problem with displaying sidebar in Ember template

Using Ember, I have a login page where I don't want to display the header or sidebar navigation for my site until the user is authenticated. Once they are logged in, I want the header and sidebar to be visible. Currently, I am achieving this by checki ...

The declaration of a 2D array within the Class is not being properly initialized

In the Circle class, I am trying to create an array of points on the perimeter that are 10 degrees apart. class Circle: def __init__(self, rad, originX, originY): self.rad = rad self.woriginX = originX self.woriginY = originY ...

Tips for incorporating a prototype in TypeScript

Exploring angular 2 has led me to create a TypeScript definition for a truncate method that I plan to implement in one of my services. truncate.ts interface String { truncate(max: number, decorator: string): string; } String.prototype.truncate = fun ...

The $watch function fails to trigger in the directive

Within my controller, I am setting a variable to true using the ng-click directive. In my custom directive, there is a need to evaluate something when this variable is true. Once evaluated, the directive then sets the variable to false. The issue I am fa ...

Exploring the process of incorporating a JavaScript library into an Angular project

I've encountered this issue before and know there are various workarounds available. I often search online for front-end design code to enhance the user experience of my projects, such as carousels, animations, and more. However, most of these project ...

Is it possible to view the frames/packets being transmitted from an EJS or HTML form to the Express backend using Express Js?

My current computer science assignment involves visually representing the data transfer process between a frontend and backend. I don't need to show the full data, just the flow of chunks and how it navigates through protocols. Could someone please g ...

How should front-end UI be updated when making changes to the database via the UI?

Seeking to optimize the process of updating UI and database values at the same time. The Scenario Currently, there is a table displaying items with columns like ID, Name, Create Date, and Favorite button on the front end. This data is fetched from the dat ...

Setting up dgrid cells to show the complete width of the information

I am developing an application that will generate a dgrid with variable column numbers and widths determined by user input. Please refer to the screenshots below for examples. The first screenshot displays a dgrid with only a few select fields, rendering n ...

PHP code iterates over an array with 4000 elements using a foreach loop

As someone who is new to php, I was able to create an array with 4000 elements (1000 arrays × 4 elements). My goal is to use a ForEach loop to properly assign 'folder', 'path', 'artist', and 'title' values 1000 tim ...

Enhance your form submission with the power of jQuery and jQuery mobile

I am attempting to create a collapsible sidebar on my website that includes a search form with a search field and submit button. In order to accomplish this, I have included the following scripts: https://code.jquery.com/jquery-1.11.3.min.js and https: ...

update the variables based on the changes in the service

I have developed a service in my application to retrieve configuration settings from the database. This service is used to display various configurations across different parts of the app. However, I am encountering an issue where the variables do not upda ...

Validating an email address without the "@" symbol or if the "@" symbol is the last character

I've been working on validating email addresses using regex, but I'm encountering an issue. The problem is that the validation fails for emails that don't contain the "@" character or have it at the end of the word. For example, if I type "a ...