Updating text within a specific div using Jquery

After spending the entire morning trying to figure it out, I am still struggling with updating text inside a clicked element without both divs getting updated at the same time. I am determined to find a solution without using IDs or additional classes.

If you want to take a look and help me out, here is the live fiddle link where you can play around with the code: https://jsfiddle.net/vinayak5192/63ujzwwn/2/

$(".edit_me").hover(function() {

  $(this).addClass('hover_edit_me');

  $(".hover_edit_me").on('click', function(e) {
    e.preventDefault();
    var big_parent = $(this);

    //edit text
    if (big_parent.attr("data-type") == 'text') {

      $("#sim-edit-text .text").val(big_parent.text());
      $("#sim-edit-text").fadeIn(500);
      $("#sim-edit-text .sim-edit-box").slideDown(500);

      $("#sim-edit-text .sim-edit-box-buttons-save").click(function() {
        big_parent.text($("#sim-edit-text .text").val());
      });
    }
  });


}, function() {
  $(this).removeClass('hover_edit_me');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="edit_me" data-type="text">This is simple title</div>
<p class="edit_me" data-type="text">This is simple paragraph</p>

<hr/>

<!-- Edit Form -->
<div class="appName_edit" id="sim-edit-text">
 <div class="sim-edit-box">
   <div class="sim-edit-box-content">
     <small>Edit Text: </small>
     <div class="sim-edit-box-content-field">
       <textarea class="sim-edit-box-content-field-textarea text"></textarea>
     </div>
   </div>
   <div class="sim-edit-box-buttons">
     <div class="btn appName_btn_save sim-edit-box-buttons-save">Save</div>
     <div class="btn appName_btn_cancel sim-edit-box-buttons-cancel">Cancel</div>
   </div>
 </div>
</div>

Answer №1

Establish a big_parent variable outside of the function body to complete the task.

var big_parent
$(".edit_me").hover(function() {

  $(this).addClass('hover_edit_me');

  $(".hover_edit_me").on('click', function(e) {
    e.preventDefault();
      big_parent = $(this);

    //edit text
    if (big_parent.attr("data-type") == 'text') {

      $("#sim-edit-text .text").val(big_parent.text());
      $("#sim-edit-text").fadeIn(500);
      $("#sim-edit-text .sim-edit-box").slideDown(500);

      $("#sim-edit-text .sim-edit-box-buttons-save").click(function() {
        big_parent.text($("#sim-edit-text .text").val());
      });
    }
  });


}, function() {
  $(this).removeClass('hover_edit_me');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="edit_me" data-type="text">This is simple title</div>
<p class="edit_me" data-type="text">This is simple paragraph</p>

<hr/>

<!-- Edit Form -->
<div class="appName_edit" id="sim-edit-text">
  <div class="sim-edit-box">
    <div class="sim-edit-box-content">
      <small>Edit Text: </small>
      <div class="sim-edit-box-content-field">
        <textarea class="sim-edit-box-content-field-textarea text"></textarea>
      </div>
    </div>
    <div class="sim-edit-box-buttons">
      <div class="btn appName_btn_save sim-edit-box-buttons-save">Save</div>
      <div class="btn appName_btn_cancel sim-edit-box-buttons-cancel">Cancel</div>
    </div>
  </div>
</div>

view the snippet

Answer №2

The issue you are experiencing is due to the fact that within the

$(".hover_edit_me").on('click', function(e) {
function, you are defining another click handler for
$("#sim-edit-text .sim-edit-box-buttons-save")
. This means that each time you click on an element to edit, hitting save will update not only that specific element but also other elements you have clicked on.

There are a couple of ways to resolve this problem. One approach is to move the declaration of big_parent and the click event for ...-save outside of the .hover_edit_me click event.

Another solution is to remove the events on the save element before adding the new one using .off(), as shown below:

$("#sim-edit-text .sim-edit-box-buttons-save").off().click(function() {

Answer №3

Take a look at the code snippet below.

An alternative way to solve this issue is by directly using the variable instead of declaring it every time like so: $big_parent = $(this);

$(".edit_me").hover(function() {

  $(this).addClass('hover_edit_me');

  $(".hover_edit_me").on('click', function(e) {
    e.preventDefault();
    $big_parent = $(this);

    //edit text
    if ($big_parent.attr("data-type") == 'text') {

      $("#sim-edit-text .text").val($big_parent.text());
      $("#sim-edit-text").fadeIn(500);
      $("#sim-edit-text .sim-edit-box").slideDown(500);

      $("#sim-edit-text .sim-edit-box-buttons-save").click(function() {
        $big_parent.text($("#sim-edit-text .text").val());
      });
    }
  });


}, function() {
  $(this).removeClass('hover_edit_me');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="edit_me" data-type="text">This is simple title</div>
<p class="edit_me" data-type="text">This is simple paragraph</p>

<hr/>

<!-- Edit Form -->
<div class="appName_edit" id="sim-edit-text">
  <div class="sim-edit-box">
    <div class="sim-edit-box-content">
      <small>Edit Text: </small>
      <div class="sim-edit-box-content-field">
        <textarea class="sim-edit-box-content-field-textarea text"></textarea>
      </div>
    </div>
    <div class="sim-edit-box-buttons">
      <div class="btn appName_btn_save sim-edit-box-buttons-save">Save</div>
      <div class="btn appName_btn_cancel sim-edit-box-buttons-cancel">Cancel</div>
    </div>
  </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

Using a data URL to stream a PDF into an iframe is only compatible with Chrome

While the code below functions properly in Chrome, it displays a blank iframe content in Firefox 15 and IE 9. <html> <head></head> <body> <p>this n that</p> <iframe type="application/pdf" widt ...

The Swiper slider becomes stuck or bounces when attempting to click and drag on the slider simultaneously

I'm currently working on some code where I am facing an issue. When I try to drag the images in the slider, it activates the hyperlinks and navigates to the image link. In an ideal scenario, dragging should move the content within the slider, and clic ...

Returning to the previous page is done by navigating back using the previous URL in Next.js

Recently, I encountered a situation where I had implemented filters on a webpage. Upon applying the filters, the URL of the page would change and additional query strings would be appended to the end. This caused an issue when navigating back using the b ...

Optimized Handlebars template using RequireJS

I recently precompiled a handlebars template manually and saved it as "testTemplate.handlebars." Now, in my code using requireJS and Backbone, I have the following function: define(['text!../templates/testTemplate.handlebars' ],function( ...

"Developing with create-react-app can be frustrating due to its sluggish performance and tendency

As I delve into the world of React, my lack of experience becomes evident. Each time I attempt to start a new project using the create-react-app command, I find myself waiting for what seems like an eternity. Discovering CodeSandbox was a game-changer - ...

The binding of a bound element within an ngIf directive does not automatically update

I recently developed an AngularJS directive where I included an ngIf directive in the template. Within this ngIf directive, there is an input element which is bound to the scope of my directive. <div ng-if="bool"><input ng-model="foo"></div ...

Issue with checkbox click event binding in Angular 6 not functioning as expected

I am currently utilizing a reactive form to display a list of heroes to the user and would like to trigger a console log message when the user selects a hero by clicking on a checkbox. The issue I am encountering is that when I print this.form in the cons ...

Unable to establish a websocket connection with either Amber or NPM, uncertain of the reason

Amber CLI (amberframework.org) - v0.11.3 Crystal 0.27.0 [c9d1eef8f] (2018-11-01) LLVM: 4.0.0 Default target: x86_64-unknown-linux-gnu npm 3.5.2 Attempting to incorporate sockets using Crystal Lang and Amber has hit a snag. Despite following the guidelines ...

Is it possible to remove htmlescape from the custom options in Magento? Can you specify which file showcases the custom

Looking to incorporate HTML into custom option labels for products on my Magento store. Unfortunately, Magento does not parse HTML by default when it is placed in the custom options interface. I suspect there may be a line like "$this->htmlEscape()" wit ...

What is the specified height for the AppBar and Toolbar components in Material-UI?

I'm trying to figure out the exact height being used in this scenario: <AppBar position="static"> <Toolbar> because I'll need that information for a calculation in another component. My current assumption is that it's 64px, b ...

Having difficulty utilizing the express.session module in conjunction with HTTPS

I need to implement authentication and session creation on a HTTPS static website using expressjs. Here is the code snippet: app.js: // Set up the https server var express = require('express'); var https = require('https'); var http ...

Managing asynchronous tasks that do not save their outcomes within the application state

Upon discovering a requirement within a vanilla JS webapp that necessitates a single JSON "definitions" object for rendering, I realized that the definitions are to be loaded through an HTTP request at the start, then read, parsed, and passed down to anoth ...

Upon transmitting the information to the server, an error message pops up saying 'Uncaught TypeError: Illegal invocation'

I'm encountering an issue with sending an ajax request in my php-script. The jquery script I'm using selects certain fields from a form and sends them as arguments to a jquery function. However, upon sending the data to the server, I receive the ...

Using Vue.js to share events and data across various components

I am currently working on an application that features a Google map with a places autocomplete controller, similar to the example provided by Google at this link. Whenever an address is searched or selected, or when the map bounds are changed, I trigger a ...

AngularJS: Exploring the Power of Restangular Library

Currently, I am exploring the wonderful Restangular library and encountering an issue while attempting to fetch JSON objects and bind them to the $scope object. Within my Factory script, I have a function that returns a list of blogs using the Restangular ...

rails/jquery/ajax: The completion function is not being triggered

My code was functioning correctly without any errors when making an AJAX call that didn't require a return value. In my Javascript (specifically coffeescript), I had the following: $.ajax({ url: "/images/" + image_id + "/" + action, type ...

A guide to accessing a provider instance manually from outside the Nest.js framework

I am currently transitioning my Express.js application to Nest.js, where some modules are already using Nest.js while others are not. For example, I have an OrderModule in Nest.js with an OrderService within its providers. Now I want to use the OrderServi ...

I'm looking to fill multiple input boxes with the same value

I am looking to pass the same value to multiple input boxes. Currently, the script below only displays in one box but I want to display the main box result in all multiple input boxes. <script type='text/javascript' src='http://code.jque ...

Removing whitespace from a Bootstrap carousel is a common task that can be easily accomplished with

What is causing the gap on my page when viewing it on a mobile device or different screen size? How can I eliminate this gap? All images have uniform height and width. ...

Tips for manipulating HTML using JavaScript and detecting the updates in ASP.NET after a postback

This is a unique challenge, and despite my efforts to find a solution in various sources, I couldn't overcome this specific scenario. I want the user to input multiple values into a single text field, like this: <div style="margin-left: 5px; disp ...