Clicking the save button in the modal updates the text on both the current tab and any previously clicked tabs

I'm looking to implement tabs that, when clicking on the edit icon, open a modal for editing the content of each tab.

The issue I'm currently encountering is that if I open the editor for one tab, close it without saving, then open the editor for another tab and save it, the changes are applied to both the previous and current tabs.

My goal is for the changes to only be saved to the currently open tab and for any unsaved changes to be canceled when clicking the close button.

var boxes = document.querySelector('.boxes');
var modal = document.querySelector('.modal');
var closeModal = document.querySelector('.closeModal');
var save = document.querySelector('.save');

boxes.addEventListener('click', (event) => {
  if (event.target.matches('.icon')) {
    var para = event.target.previousElementSibling;
    var textBox = document.querySelector('.textBox');
    textBox.value = para.textContent;
    modal.style.display = "block";
    save.addEventListener('click', () => {
      para.textContent = textBox.value;
      modal.style.display = "none";
    });
    closeModal.addEventListener('click', () => {
      modal.style.display = 'none';
    })
  }
})
* {
  margin: 0px;
  padding: 0px;
  box-sizing: border-box;
}

.box {
  margin-bottom: 20px;
  padding: 20px;
  background-color: rgb(73 191 214);
  width: 200px;
}

.box .para {
  color: white;
  font-family: arial;
  font-size: 18px;
}

.box .icon {
  font-size: 30px;
  color: white;
  cursor: pointer;
}

.modal {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  background-color: rgba(0, 0, 0, 0.055);
  display: none;
}

.modalContent {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: white;
  padding: 20px;
  box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, 0.2);
  border-radius: 10px;
}

.textBox {
  resize: none;
  padding: 10px;
  font-family: arial;
  font-size: 18px;
  outline: none;
  width: 100%;
  height: 150px;
  border: 2px solid #ececec;
}

.save {
  display: block;
  margin: 20px auto;
  padding: 10px 15px;
  background-color: rgb(247, 42, 121);
  color: white;
  font-size: 16px;
  font-family: arial;
  outline: none;
  border: none;
  cursor: pointer;
}

.closeModal {
  float: right;
  font-size: 35px;
  color: gray;
  cursor: pointer;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.2/css/all.min.css" integrity="sha512-HK5fgLBL+xu6dm/Ii3z4xhlSUyZgTT9tuc/hSrtw6uzJOvgRr2a9jyxxT1ely+B+xFAmJKVSTbpM/CuL7qxO8w==" crossorigin="anonymous" />

<div class="boxes">
  <div class="box">
    <p class="para"> This is first text for editing . </p>
    <i class="fas fa-edit icon"></i>
  </div>
  <div class="box">
    <p class="para"> This is second text for editing . </p>
    <i class="fas fa-edit icon"></i>
  </div>
  <div class="box">
    <p class="para"> This is third text for editing . </p>
    <i class="fas fa-edit icon"></i>
  </div>
  <div class="box">
    <p class="para"> This is fourth text for editing . </p>
    <i class="fas fa-edit icon"></i>
  </div>
  <div class="box">
    <p class="para"> This is fifth text for editing . </p>
    <i class="fas fa-edit icon"></i>
  </div>
</div>
<div class="modal">
  <div class="modalContent">
    <span class="closeModal"> &times; </span>
    <textarea class="textBox"></textarea>
    <button class="save"> SAVE </button>
  </div>
</div>

Answer №1

To optimize your code, it's recommended to separate your event handlers from the click function and create a designated placeholder for the clicked box.

const boxes = document.querySelector('.boxes');
const modal = document.querySelector('.modal');
const closeModal = document.querySelector('.closeModal');
const save = document.querySelector('.save');
const textBox = document.querySelector('.textBox');
let currentPara;
boxes.addEventListener('click', (event) => {
  if (event.target.matches('.icon')) {
    currentPara = event.target.previousElementSibling;
    textBox.value = currentPara.textContent;
    modal.style.display = "block";
  }
})

save.addEventListener('click', () => {
  currentPara.textContent = textBox.value;
  modal.style.display = "none";
});
closeModal.addEventListener('click', () => {
  modal.style.display = 'none';
})
* {
  margin: 0px;
  padding: 0px;
  box-sizing: border-box;
}

.box {
  margin-bottom: 20px;
  padding: 20px;
  background-color: rgb(73 191 214);
  width: 200px;
}

.box .para {
  color: white;
  font-family: arial;
  font-size: 18px;
}

.box .icon {
  font-size: 30px;
  color: white;
  cursor: pointer;
}

.modal {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  background-color: rgba(0, 0, 0, 0.055);
  display: none;
}

.modalContent {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: white;
  padding: 20px;
  box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, 0.2);
  border-radius: 10px;
}

.textBox {
  resize: none;
  padding: 10px;
  font-family: arial;
  font-size: 18px;
  outline: none;
  width: 100%;
  height: 150px;
  border: 2px solid #ececec;
}

.save {
  display: block;
  margin: 20px auto;
  padding: 10px 15px;
  background-color: rgb(247, 42, 121);
  color: white;
  font-size: 16px;
  font-family: arial;
  outline: none;
  border: none;
  cursor: pointer;
}

.closeModal {
  float: right;
  font-size: 35px;
  color: gray;
  cursor: pointer;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.2/css/all.min.css" integrity="sha512-HK5fgLBL+xu6dm/Ii3z4xhlSUyZgTT9tuc/hSrtw6uzJOvgRr2a9jyxxT1ely+B+xFAmJKVSTbpM/CuL7qxO8w==" crossorigin="anonymous" />

<div class="boxes">
  <div class="box">
    <p class="para"> This is first text for editing.</p>
    <i class="fas fa-edit icon"></i>
  </div>
  <div class="box">
    <p class="para"> This is second text for editing.</p>
    <i class="fas fa-edit icon"></i>
  </div>
  <div class="box">
    <p class="para"> This is third text for editing.</p>
    <i class="fas fa-edit icon"></i>
  </div>
</div>
<div class="modal">
  <div class="modalContent">
    <span class="closeModal"> &times; </span>
    <textarea class="textBox"></textarea>
    <button class="save"> SAVE </button>
  </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

What is the method for displaying x-axis dates below a highchart?

I'm encountering an issue with Highcharts where dates are not showing under the chart when passing series data as an array of objects. See result image The documentation mentions using an object instead of an array ([1649153340000, 45]docs I need t ...

Ways to effectively store continuous scale data in a database

I am currently running a straightforward Node.js server (using Express) on my local machine on port 8000. By utilizing the npm package serialport, I have successfully connected to a scale and am able to retrieve its weight in a continuous manner as shown ...

npm WARNING: The package @angular-devkit/[email protected] is in need of a peer dependency xxxx, however no installation for this dependency has

Attempting to launch an angular project and encountering the following errors: $ npm install npm WARN @angular-devkit/[email protected] requires a peer of @angular/compiler-cli@^14.0.0 but none is installed. You must install peer dependencies yoursel ...

Client.db is undefined error encountered in MongoDB backend API

I'm having trouble retrieving data from a collection in my MongoDB backend. Every time I try, I encounter an error stating that the client is not defined. Has anyone else experienced this issue and knows how to resolve it? Error: Client is not define ...

Displaying array elements on a webpage using JavaScript in HTML

Looking to display multiple blocks in HTML using a JavaScript array. The array contains names such as: var name=['amit','mayank','jatin'];. I need to repeat a certain portion of code in order to show the elements of the array, ...

Error encountered: The JSONP request to https://admin.typeform.com/app/embed/ID?jsoncallback=? was unsuccessful

I encountered an issue with the following error message: Error: JSONP request to https://admin.typeform.com/app/embed/id?jsoncallback=? Failed while trying to integrate a typeform into my next.js application. To embed the form, I am utilizing the react-ty ...

The alignment of elements on the right and left sides is not functioning as intended

I've been facing an issue with the alignment of my floats on my brand new website www.unicmedia.nl/case/oranje. Surprisingly, they seem to work fine in IE this time, but Firefox and Chrome are completely out of sync. Despite trying numerous solutions ...

What is the best way to reload DataTables using an ajax/error callback?

In my code, I am customizing the default settings of DataTables like this: $.extend(true, $.fn.dataTable.defaults, { lengthChange: false, deferRender: true, displayLength: 25, stateSave: false, serverSide: true, processing: true, ...

OceanWP Theme with a Fixed Navigation Bar

Currently utilizing the oceanwp theme, I'm aiming to create a topbar that vanishes while scrolling and have the menu smoothly transition to the topbar location with some opacity. I attempted the following code snippet: #site-header { position: fixe ...

Using JavaScript to locate and emphasize specific words within a text, whether they are scattered or adjacent

I need help finding a JavaScript code for searching words in a text using a form and a search button. I found one that works for multiple words in a row, but it doesn't work if the words are mixed up. What changes should be made to fix this issue? An ...

Shadows persist despite light intensity being reduced to 0 during runtime

Struggling to figure out how to get rid of these persistent shadows... During runtime, I attempt: light.intensity = 0.0; This makes the scene darker (which is good), but the shadows created by the light remain visible. I've experimented with both ...

Generate spacing between rows of content in HTML or CSS without affecting the spacing between lines of text

In my R Markdown document in R, I want to replace the header labeled "Preface" with grey lines for visual indication. Here's the code snippet I've tried: :::{#preface} <p> Text </p> ::: However, there seems to be no margin at the beg ...

Steps for implementing an <h1> element with the React Material UI theme

I have chosen the 'dark' theme and would like to apply it to an h1 element. How can I achieve this? The method below does not yield the desired result: <MuiThemeProvider theme={theme}> <h1>Page Title</h1> ... The following ...

I am having difficulty with the fadeIn animation not working as expected in my situation

http://jsfiddle.net/9w0v62fa/1/ Instead of using opacity 0 and 1 in two different places, which I find redundant, I attempted to utilize the CSS animate property. However, I couldn't get it to work. Here is my code: .btn{ background:blue; pa ...

What is the reason for index always being not equal to 0?

<script> var index = 0; $.getJSON("./data/data.json", function(json) { $.each(json, function(data) { var html = ""; if(index == 0) { console.log(index + " fir ...

Tips for arranging div elements in a grid-like matrix layout

I am facing a challenge in arranging multiple rectangular divs into a grid structure with 10 columns and 10 rows. The CSS styles for the top, bottom, left, or right positions must be in percentages to accommodate zoom in and out functionality without overl ...

The Heroku Node.js application encountered an issue when trying to apply the style due to an incompatible MIME

As a complete beginner in Node.js and Express, I am encountering some errors from the console. When trying to load my CSS file from '', I receive the following error: "Refused to apply style because its MIME type ('text/html') i ...

Selenium for handling multiple input fields

Having some trouble figuring out how to input values for selecting a building. Initially, there are two empty input fields for selecting a building. As you enter one, it should add an additional empty input field. I'm struggling with the indexing and ...

Utilize Office Scripts to update values across numerous worksheets

Looking for ways to improve the performance of this script, as it currently takes 45 seconds to run. Any ideas? function main(workbook: ExcelScript.Workbook) { try { const sheets = workbook.getWorksheets(); for (let sheet of sheets) { const break ...

Using Java script to parse and interpret a JSON file

I have a JSON file that follows this structure. Being new to JavaScript, I am looking for guidance on how to extract each key and its associated value. Can someone help me understand where to begin? AuthServer.Web": { "stuff": { "evenmore st ...