Troubleshooting Issue with jQuery replaceWith in Loop

Trying to make it so that when the update button is clicked, the text on the left side becomes an input box:

Click the update button and the text on the left will be an input box

However, instead of just one input box appearing, all the text on the left side is being replaced with INPUT boxes: all text left side is affected

New to jQuery and not sure how to use a unique id to prevent this. Also seeking guidance on editing the affected table in MySQL.

Code snippet:

<table class="table no-margin">
              <thead>
              <tr>
                <th width="250px">Category</th>
                <th width="20px"> </th>
                <th width="20px"> </th>
              </tr>
              </thead>
              <tbody>
              <?php 
                while ($rows = mysql_fetch_array($result)) {
                  $tcategory = $rows['vCategory'];
                  $cid = $rows['id'];
              ?>
              <tr>
                <td>
                <?php echo '<div class="editable">'. $tcategory .' </div>'; ?>

                </td>
                <td><button id="edit" class="btn btn-block btn-xs btn-success"> Update</button> </td>
                <td><button class="btn btn-block btn-xs btn-danger">  Delete</button> </td>

                <?php
                }
                ?>
                <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
                <script>
                  $("#edit").click(function() {
                    var $this = $(this);
                    if($this.attr('editing') != '1') {
                      $this.text('Save').attr('editing', 1);
                      $(document).find('.editable').each(function() {
                        var input = $('<input class="editing" />').val($(this).text());
                        $(this).replaceWith(input);
                      });
                    }else {
                      $this.text('Update').removeAttr('editing');
                      $(document).find('input.editing').each(function() {
                        var div = $('<div class="editable" />').text($(this).val());
                        $(this).replaceWith(div);
                      });
                    }
                  });
                </script>
                </tr>
                <form>
                <tr>
                  <td><input type="text" class="form-control" name="addCategory" placeholder="Enter New Category"></td>
                  <td><input type="submit" class="btn btn-block btn-sm btn-success" value="Add"></td>
                </tr>
                </form>   

              </tbody>
            </table>

Answer №1

Assign the same class to all edit buttons and remove the edit ID as IDs should be unique. You can try implementing the following:

https://jsfiddle.net/v2bxdttz/

Utilize

$(this).closest('tr').find('.editable').each(function() {

instead of

 $(document).find('.editable').each(function() {

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

I'm really confused as to why I am receiving an undefined error in this code. Can someone please assist

I'm encountering an issue with getting undefined in this section of code. Is there a way to fetch the data using useEffect, and once everything is loaded, how can I efficiently store it in a useState variable and then display the necessary content? co ...

Display JSON information in a grid using JQuery

I'm on the lookout for a simple json grid plugin to make my life easier. I need to populate a grid using JSON/Ajax, but the catch is that the amount of data or columns will vary each time, so it needs to be able to adapt accordingly. For example, a p ...

The error stating that document.getElementById(...) is null has occurred within RSForms due to a TypeError

Issue: When clicking on the form to continue, a TypeError: document.getElementById(...) is null error occurs. Can anyone help me fix this problem? When I click on the continue button, it calls the function submitForm. <script type="text/javascript"> ...

Listening for dates in NodeJS and triggering callbacks

Is there a method or module available that allows me to monitor the date and trigger a specific action when a certain condition is met without relying on setTimeOut? What I am looking for: if(currentHour==="08:00:00"){ doJob() } EDIT : To clarify, wha ...

What is the method for defining the current date variable within a .json object?

When using a post .json method to send an object, I encounter the following situation: { "targetSigningDate": "2021-09-22T21:00:00.000Z" } The "targetSigningDate" always needs to be 'sysdate'. Rather than manually c ...

Strangely unusual issues with text input boxes

So I've set up two textareas with the intention of having whatever is typed in one appear simultaneously in the other. But despite my best efforts, it's not working as expected. Here's the code snippet: <script> function copyText () { ...

Erase jQuery from the text

I am struggling with splitting or removing text from a filename. For example, if I have filenames like: 200726100_50-0002.JPG 230514008_60-0001.JPG The desired result should be: 230514008_60.JPG 200726100_50.JPG Am I not using the split function cor ...

Obtaining the Div ID After Clicking on a Link

I'm attempting to fade out a box once the X in that box is clicked. I haven't been able to make it work even after searching on Google. I managed to get it working when clicking the div itself using $(this), but my goal is for it to work when the ...

Leverage PHP to retrieve information from a JSON file and integrate it into a dropdown menu on an HTML

I've been given a task to develop a PHP routine that will extract the ISO code and name from a geojson file for use in a dropdown list of countries on a website. This is completely new to me and I'm finding it difficult to understand the documen ...

Troubleshooting Problems with Promises in Node.js Express

I am currently developing a Node.JS/Express application with Jade as the template engine, but I am encountering some unexpected behavior. The issue arises when trying to retrieve data from a mock API and pass it to my Jade template. Despite confirming tha ...

Attempting to design a customized tooltip for an SVG element embedded within the HTML code

Recently, I've delved into Js with the goal of creating an interactive pronunciation guide using inline svg. If you're curious to see what I've done so far, check it out here. My current focus is on incorporating basic styled tooltips that ...

What is the best way to save variables in PHP for later use in various scripts?

As a newcomer to PHP programming, I am facing a rather simple issue that I haven't been able to solve despite trying various methods and searching online for a solution. Any assistance you can provide would be greatly appreciated. The problem at hand ...

Issue with Orgchart JS: The requested resource does not have the 'Access-Control-Allow-Origin' header present

Currently, I am developing a program to create organization charts using orgchart.js and simple PHP. This project does not involve any frameworks, but unfortunately, I encountered the following error: CORS policy is blocking access to XMLHttpRequest at & ...

"The use of Node.js and Express.js in handling HTTP requests and responses

I am intrigued and eager to dive deep into the request and response cycle of backend development. Here's my query: I have a node.js express framework up and running. The app is launched and all functions are primed and ready for requests. app.use(&a ...

Adding a class name to the three active, visible, and shown slides in SwiperJS is a simple process that can be done by

Currently, I am working on customizing a carousel in Swiper with slidesPerView={3}. My goal is to style the sliders that are not visible on the screen. I have made multiple attempts to achieve this: First, I tried adding the attribute slideActiveClass="sw ...

Using an external module in a Vue SFC: a beginner's guide

Recently delving into Vue, I'm working on constructing an app that incorporates Typescript and the vue-property-decorator. Venturing into using external modules within a Single File Component (SFC), my aim is to design a calendar component utilizing t ...

Transforming a function into its string representation | 'function(){...}'

func=function() {foo=true} alert(JSON.stringify(func)); alerts "undefined" obj={foo: true} alert (JSON.stringify(obj)); alerts: "{foo: true}" Have you ever wondered why JSON.stringify() doesn't work for a "function object"? It seems that when tryi ...

Having trouble editing a record in Vue.js/Vuetify/Axios after it has been created

After creating a new record, I encounter an issue where updates don't reflect in the database until I refresh the page. This behavior has left me puzzled about its cause. The sequence of events goes as follows: 1) New record creation --> data sent t ...

The server's request is being processed through jQuery's ajax functionality

Recently, I've started working with jQuery and AJAX. Essentially, the webpage sends an HTTP post request, and the server-side DLL responds by writing a JSON-formatted response back to the page. I'm trying to understand how to handle this response ...

Identify the geometric figure sketched on the canvas using the coordinates stored in an array

After capturing the startX, startY, endX, and endY mouse coordinates, I use them to draw three shapes (a line, ellipse, and rectangle) on a canvas. I then store these coordinates in an array for each shape drawn and redraw them on a cleared canvas. The cha ...