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>';
}
};