What steps do I need to take to create a delete button that will effectively remove a bookmark from an array?

Currently, I have created a form that allows users to input the website name and URL. Upon clicking the submit button, the output displays the website name along with two buttons: 1. one for visiting the site 2. another for removing the bookmark using onClick

However, I am facing an issue where the remove button does not function as intended:

<!DOCTYPEhtml>
<htmllang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JSBOOKMARK</title>
    <link rel="stylesheet" href="css/bootstrap.min.css" />
    <link rel="stylesheet" href="css/all.css">
    <link rel="stylesheet" href="css/index_style.css" />
    <script src="js/jquery-3.4.1.min.js"></script>
    <script src="js/popper.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
</head>

<body>
    <div class="container pt-5 pb-5">
        <h1 class="pb-5 pl-3 font-weight-bold">BookMark</h1>
        <hr>
        <div class="body m-auto text-center py-5">
            <h2 class="py-2">Bookmark your favorite sites</h2>
            <form class="w-75 m-auto" id="myForm">
                <div class="form-group">
                    <label for="Site_Name" class="py-2">Site Name</label>
                    <input type="text" class="form-control" id="siteName" placeholder="Bookmark Name" required>
                </div>
                <div class="form-group">
                    <label for="Site_URL" class="py-2">Site URL</label>
                    <input type="text" class="form-control" id="siteUrl" placeholder="website URL" required>
                </div>
                <button id="sub" class="btn btn-primary">Submit</button>
            </form>
        </div>
        <div class="container mt-3">
            <div class="row shadow-none p-3 mb-5 bg-light rounded">
 <!--dispalyarea-->
                <div class="col">
                    <div id="bookmarkCon"></div>
                </div>
            </div>
        </div>
        <hr>
        <div class="footer">
            <p>&copy;2019 Bookmarker Inc.</p>
        </div>
    </div>
    <script src="js/jquery-3.4.1.min.js"></script>
    <script src="js/popper.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
    <script src="js/main.js"></script>
</body>

</html>

//Java script code :

var bookMname = document.getElementById("siteName");
var bookUrl = document.getElementById("siteUrl");
var btn = document.getElementById("sub");
var bookMarks = [];

btn.onclick = function () {
    addBookMark();
    displayData();
    reset();

}

function addBookMark() {
    var bookMark = {
        bookMarkName: bookMname.value,
        url: bookUrl.value,
    }

    bookMarks.push(bookMark);

}

function displayData() {

    /**local var */
    var data = "";

    for (var i = 0; i < bookMarks.length; i++) {

        data += "<div><span class='mr-5 font-weight-bold h1 text-uppercase'>" + bookMarks[i].bookMarkName + "  " + "</span><span>" + ' <a class="btn btn-primary mr-4" target="_blank" href="' + bookMarks[i].url + '">Visit</a> ' + "</span></div>"

    }

    document.getElementById("bookmarkCon").innerHTML = data;
}

function displayData() {

    /**local var */
    var data = "";

    for (var i = 0; i < bookMarks.length; i++) {

        data += "<div><span class='mr-5 font-weight-bold h1 text-uppercase'>" +    bookMarks[i].bookMarkName + "  " + "</span><span>" + ' <a class="btn btn-primary mr-4" target="_blank" href="' + bookMarks[i].url + '">Visit</a> ' + "</span><span onclick='dD()'>" + ' <a class="btn btn-danger mr-4" href="' + bookMarks[i].url + '">Delete</a> ' + "</span></div>"

    }

    document.getElementById("bookmarkCon").innerHTML = data;
}

function reset() {
    document.getElementById("myForm").reset();

}


//Delete function

function dD() {

    for (var i = 0; i < bookMarks.length; i++) {
        if (bookMarks[i].url == bookMarks.url) {
            // Remove from array
            bookMarks.splice(i, 1);
        }
    }
}

console.log()

Upon trying to use the delete button, I face redirection to an error page. How can I resolve this issue with the delete functionality?

Answer №1

Your anchor tag for deletion currently directs to a new page:

    <a class="btn btn-dengar mr-4" href="http://your-bookmark-url">Delete</a>

To prevent this behavior, modify the tag to a button instead:

    `<button class="btn btn-danger mr-4"
       onclick="handleDelete(${i});">Delete</button>`

Next, update your Delete button's handleDelete() function to eliminate the bookmark and refresh the DOM:

    function handleDelete(index) {
      // remove from bookMarks array
      bookMarks.splice(index, 1);
      // update the DOM
      displayData();
    }

Here is the complete working version:

const bookMname = document.getElementById("siteName");
const bookUrl = document.getElementById("siteUrl");
const btn = document.getElementById("sub");
let bookMarks = [];

btn.onclick = function() {
  addBookMark();
  displayData();
  reset();
};

function addBookMark() {
  const bookMark = {
    bookMarkName: bookMname.value,
    url: bookUrl.value,
  };

  bookMarks.push(bookMark);
}

function displayData() {
  let data = "";

  for (let i = 0; i < bookMarks.length; i++) {
    data +=
      `<div>
          <span
            class="mr-5 font-weight-bold h1
              text-uppercase">${bookMarks[i].bookMarkName}</span>
          <a class="btn btn-primary mr-4"
            target="_blank"
            href="${bookMarks[i].url}">Visit</a>
          <button class="btn btn-danger mr-4"
            onclick="handleDelete(${i});">Delete</button>
        </div>`;
  }
  document.getElementById("bookmarkCon").innerHTML = data;
}

function reset() {
  document.getElementById("myForm").reset();
}

function handleDelete(index) {
  bookMarks.splice(index, 1);
  displayData();
}
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1a6a756a6a7f683470695a2b342b2b2c342a">[email protected]</a>/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />
<div class="container pt-5 pb-5">
  <h1 class="pb-5 pl-3 font-weight-bold">BookMark</h1>
  <hr>
  <div class="body m-auto text-center py-5">
    <h2 class="py-2">Bookmark your favorite sites</h2>
    <form class="w-75 m-auto" id="myForm">
      <div class="form-group">
        <label for="siteName" class="py-2">Site Name</label>
        <input type="text" class="form-control" id="siteName" placeholder="Bookmark Name" required>
      </div>
      <div class="form-group">
        <label for="siteUrl" class="py-2">Site URL</label>
        <input type="text" class="form-control" id="siteUrl" placeholder="website URL" required>
      </div>
      <button id="sub" class="btn btn-primary">Submit</button>
    </form>
  </div>
  <div class="container mt-3">
    <div class="row shadow-none p-3 mb-5 bg-light rounded">
      <!--dispalyarea-->
      <div class="col">
        <div id="bookmarkCon"></div>
      </div>
    </div>
  </div>
  <hr>
  <div class="footer">
    <p>&copy;2019 Bookmarker Inc.</p>
  </div>
</div>

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

How can one "organize" a dictionary from JSON in Swift to visualize it in a time-series chart?

While it's true that a dictionary is unsorted by definition, I need the date key to be sorted in order to plot it on a graph, similar to a stock price plot over the last 30 days. I've tried two methods from this source, but they didn't work ...

Error message "Module not found in Vue" occurs when changing image URL to an online image

I am currently working on a dynamic image display feature where I retrieve image names as strings from a backend. To manage a large number of images, I plan to store them online while maintaining the same logic for displaying them. Previously, I achieved t ...

"What are the reasons for encountering a '404 not found' error with Django when accessing a

I recently developed a Django script that utilizes a Python parser to navigate the web. I have set up AJAX to send requests to this Django script, but I am encountering a 404 error for the URL when the Ajax runs. Can you help me understand why this is occu ...

Do Material-UI pickers only validate on blur, not on change events?

When you type inside the DatePicker component, validation is triggered immediately. Is there a way to trigger validation on blur instead of onChange when using @material-ui/pickers with material-ui v4 Passing the value to the blur function should work a ...

"Encountered a Chrome RangeError: The call stack size limit was exceeded while utilizing jQuery's $

As part of my job, I am currently evaluating a web application that involves fetching a substantial amount of data from the server. The data is received as a JSON object using the $.ajax function. It contains numerous sub-objects which I convert into array ...

"Encountering a 404 error with the angular2-in-memory-web-api

Currently, I am in the process of developing a 5 minute application using Angular 2 with reference to this particular guide: https://angular.io/docs/ts/latest/tutorial/toh-pt6.html. While working on the HTTP section, I encountered a 404 error due to the a ...

Utilizing the array.map method to access the key of an object within an array of arrays in TypeScript

Can I utilize array.map in TypeScript to apply a function with the parameter being the key of an object within an array? I have an array containing objects which have keys 'min' and 'max'. I am looking to use something like someArrayFun ...

Use jQuery to refresh the jQuery sparkline chart after fetching data asynchronously

Background Utilizing the jquery.sparkline library to generate Pie Charts. The data for these charts is stored in an array. Upon initial page load, a web-service call is made (using .ajax) to fetch the data. The callback function associated with this call ...

Tips for selecting multiple elements with the same class name in Protractor for Angular:1. Use the `element

Snippet of HTML code: <div class="block ng-scope" ng-repeat="skills in data.primary_skills"> <div class="block skillsLineItem" ng-class="{manditorySkillsLineItem:skills.mandatory, skillsLineItem:!skills.mandatory}"> < ...

Utilizing jQuery AJAX to Send an HTML Array to PHP

In my current HTML forms and jQuery AJAX workflow within the Codeigniter Framework, I've encountered a common issue that has yet to be resolved to suit my specific requirements. Here's the situation: HTML - The form includes an array named addre ...

Guide on transforming JSON lines that have been escaped into a collection of beans

Java POJO: import android.os.Parcel; import android.os.Parcelable; import com.gongzelong.duolingowordsearch.utils.ParcelableUtils; import com.google.gson.annotations.SerializedName; import java.util.List; public class WordSearch implements Parcelable ...

What is the best way to use checkboxes to highlight table rows in Jquery Mobile?

I have a Jquery Mobile site with a table. Each table row contains checkboxes in the first cell. I am trying to achieve the following: a) Highlight a row when the user clicks on it b) Highlight a row when the user checks the checkbox I have made progr ...

It appears that Apexcharts is not compatible with React/Next.js

Issue Encountering a crash in my Next.js/React/Node application whenever I utilize import Chart from "react-apexcharts" in any file. Upon attempting to access the app, an error message is displayed: Server Error ReferenceError: window is not ...

creating a randomized location within an HTML element using JavaScript

Trying to figure out how to randomly generate a position within an HTML div. I've come up with a JavaScript function that looks like this: function randomInRange(min, max) { return(Math.floor((Math.random() * (max - min) + 1) + min)); } My ...

Tips for updating JS and CSS links for static site deployment

As I develop my static site using HTML files served from a simple web server, I want to use local, non-minified versions of Javascript code and CSS files. However, when it comes time to deploy the site, I would like to refer to minified versions of these s ...

Having trouble receiving a complete response when making an ajax request to fetch an entire webpage

Currently, I am experimenting with J-Query Ajax functionality. My goal is to send a request in order to retrieve the entire HTML data of a page that I have hosted on bitbaysolutions.com. The issue arises when I load this URL and execute document.getElement ...

I keep receiving a JavaScript alert message saying "undefined."

When I try to alert the item_id after giving input in the quantity textbox, I am receiving an undefined JavaScript alert. The code snippet below is not displaying the alert as expected: var item_id=$("#item_"+i).val();alert(item_id); In addition, my mode ...

AngularJS Firebase Login Scope Value Not Retained After Refresh

I have stored my unique username in the variable "$scope" and I am trying to access it from different views once the user logs in, using: However, when I refresh the page immediately after the user successfully signs in, the value of "$scope" goes bac ...

Tips for retrieving information from an API and displaying it in a table

I'm struggling to retrieve data (an array of objects) from an API using a Token and display them in a table using Material-UI. However, I keep encountering the following error: Uncaught (in promise) SyntaxError: Unexpected token 'A', "Access ...

JavaScript enables users to store over 5 megabytes of data on their client devices

Is there a way to store more than 5mb in the client browser? I need this functionality across various browsers including Firefox, Chrome, Internet Explorer, Safari (iOS), and Windows Phone 8 Browser. Initially, localStorage seemed like a viable option as i ...