The edit button for an element should only modify that specific element, but instead it is making changes to all elements

Currently, I am working on creating an edit function for a favorites bar. The issue I am facing is that when I attempt to edit one box, all the previously clicked boxes are also being edited. You can find the complete code in this jsfiddle link: https://jsfiddle.net/1exrf9h8/1/

I'm puzzled as to why my editFavorite function is updating multiple boxes instead of just the selected one.

function clickEdit(input, title, url, plus, editIcon, anchorEdit, editBtn)
{
  let i = editIcon.length - 1;

  editIcon[i].addEventListener("click", function(event){
    input.style.display = "block";
    title.value = plus[i + 1].textContent;
    url.value = anchorEdit[i].href;
    console.log(i);
    console.log(anchorEdit[i]);
    editFavorite(anchorEdit[i], url, title, input, editBtn);
  });
}

function editFavorite(changed, url, title, input, editBtn)
{
  editBtn.addEventListener("click", function(){
    changed.href = url.value;
    changed.textContent = title.value;
    input.style.display = "none";
  });
}

Answer №1

It seems that there are some issues with your current approach in terms of logic, architecture, and the event handler being used. Let's try a more OOP approach to solve these problems and gain a better understanding of the process.

Each favorite will be treated as an independent object capable of creating and updating itself.

function favorite(newTitle, newUrl) {
  this.element = container.appendChild(document.createElement("div"));
  this.title = this.element.appendChild(document.createElement("h2"));
  this.url = this.element.appendChild(document.createElement("h2"));

    this.update = (newTitle, newUrl) => {
      this.title.textContent = newTitle;
      this.url.textContent = newUrl;
    }

    this.createButton = () => {
      button = this.element.appendChild(document.createElement("button"));
      button.append("Edit");
      button.addEventListener("click", () => {
        let titleInput = document.getElementById("title").value;
        let urlInput = document.getElementById("url").value;

        this.update(titleInput, urlInput);
      })
  }

  this.update(newTitle, newUrl);
  this.createButton();
}

We can then include a simple form where users can input data for editing existing favorites or creating new ones.

<input id="title" type="text" name="title" placeholder="Title">
<input id="url" type="text" name="url" placeholder="Url">
<button id="submit">Create New</button>

Next, we implement the submit functionality.

  document.getElementById("submit").addEventListener("click", () => {
    let titleInput = document.getElementById("title").value;
    let urlInput = document.getElementById("url").value;

    if (!titleInput.length || !urlInput.length) return;
    let newFavorite = new favorite(titleInput, urlInput);
    container.appendChild(newFavorite.element);
 });

https://jsfiddle.net/p50L27us/48/

Answer №2

An issue arises with the editFavorite function because each time it is called, a new listener is automatically initiated, resulting in multiple listeners being active simultaneously.

The solution lies in adding "{once : true}" as an option within the event listener, which ensures that the listener will only trigger once.

function editFavorite(changed, url, title, input, editBtn)
{
  editBtn.addEventListener("click", function(){
    changed.href = url.value;
    changed.textContent = title.value;
    input.style.display = "none";
  },{once : true});
}

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

Customize the appearance of alert boxes in ajax requests

Is there a way to customize the default ajax alert box? I currently have code that deletes a user and reloads the current page. It functions properly, but I want to enhance the styling of the alert box that appears before the user is deleted. function d ...

"The error message "Node JS, MYSQL connection.query is not a valid method" indicates

db_config.js: const mysql = require('mysql'); var connection = mysql.createConnection({ host: 'localhost', user: 'root', password: '', database: 'test' }) connection.connect(function(err) ...

What is the process for populating dropdown options from state?

I've been struggling to populate a select element with options based on an array in state. Despite trying various methods, the code snippet below seems to be the most detailed (I'm still getting familiar with React after taking a break for a few ...

How can I trigger the execution of the script when an asp button is clicked?

Instead of using the script within a div element by default, I am interested in triggering the script on button click. <div class="fb-login-button" data-show-faces="true" data-width="400" data-max-rows="1"> </div> <script l ...

What is preventing me from directly assigning properties to my data object?

Struggling to access my question props in order to assign its property directly into my data properties. Although I can use the property directly from my template, I am unable to assign it into the data. Currently, I can only retrieve the value of props f ...

What is the best way to retrieve the value of a <div> element using AngularJs?

Can anyone guide me on how to retrieve the value of a clicked <div> in AngularJs? <div ng-repeat="y in data"> <span ng-click="showDetails()" ng-model="searchText" >{{ y }} </span><br/> </div> Shown below is ...

Is it possible to retrieve a JSON response by making a jQuery.ajax request to an appengine URL?

Attempting to retrieve response data via ajax from the following URL: http://recipesid.appspot.com/api.user?method=user.query&[email protected] Encountering issues when trying to run the code. Please assist in resolving this problem. $.ajax({ ...

Tips for centering Navigation image as screen size decreases

I'm currently in the process of creating a navigation bar, and here's what I have so far: <!-- #region Navigation --> <div class="container "> <nav class="navbar navbar-fixed-top bg-white box-shadow " style= ...

The height of Bootstrap 4 beta columns causes a conflict with the navigation bar,

Using Bootstrap Beta 4, I've encountered an issue where my nav element is overlapping my column div. What could be the cause of this problem? <html> <head> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstr ...

Creating a "Mark as Read" function using localStorage

Looking for a solution to persist the state of "Mark as Read" or "Mark as Unread" even after refreshing the page? Want to use localStorage to save this data? Here's an example of code snippet for toggling between these states: function readunread() { ...

What is the process by which React loads and runs JSX content?

What is the method used to identify and handle JSX code? <script src="src/main.js" type="text/babel"></script> ...

perplexed by the pair of buttons

Is it possible to change the default behavior of an ASP.NET button so that pressing the ENTER key on the keyboard submits a different button instead? If so, how can this be done? ...

NodeJs guide on removing multiple documents from a MongoDB collection using their _id values

Consider the following array of _ids: ["a12s", "33qq", "121a"] In MongoDB, there are methods such as deleteMany, which allows deletion based on specific queries: var myquery = { address: 'abc' }; dbo.collection("customers").deleteMany(myque ...

Bug in timezone calculation on Internet Explorer 11

I've spent hours researching the issue but haven't been able to find any effective workarounds or solutions. In our Angular 7+ application, we are using a timezone interceptor that is defined as follows: import { HttpInterceptor, HttpRequest, H ...

Adjusting font size in CSS for HTML websites

Having some trouble adjusting the font size on my HTML webpage using CSS - for some reason, the "font-size" property isn't cooperating: Below is the snippet of HTML code for my site: And here's a brief look at the accompanying CSS code: I&apos ...

The JQuery loading symbol does not prevent keyboard interactions

I successfully implemented a Jquery busy indicator in my application using the following link: However, I noticed that even though it prevents users from clicking on input elements while loading, I can still navigate to these elements by pressing the tab ...

Generating random indexes for the Answer button to render

How can we ensure that the correct button within the Question component is not always rendered first among the mapped incorrect buttons for each question? Is there a way to randomize the positions of both correct and incorrect answers when displaying them, ...

Implementing ordering and limiting of elements in NestJS TypeORM relations

I am new to typeorm and relationships. I am currently facing some challenges and feeling a bit confused. I have a question regarding sorting relations in typeorm by id or createdDate without explicitly mapping them and limiting the number of elements. Here ...

Ways to retrieve component information externally from export

As a newcomer to Vue, I've been experimenting with it before diving into our project, but I've encountered a problem. Typically, when we create an instance like "var app = new Vue ... etc.," we can access its data using app.data. But how do we a ...

Replace the element's style using a JavaScript object

While there are numerous versions of this query, the existing answers fail to provide in-depth analysis. Query: How does this result in a height of 200 pixels? Consider the following code snippet: var el = document.querySelector('#r'); cons ...