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

Strategies for improving the efficiency of HTML and styles in a generated document

Generating the invoice printing form layout using dynamically created Razor views through RazorEngine can result in messy and hard-to-read code. The repetitive use of words like top, left, width, and height makes it challenging for human inspection and deb ...

What is the reason behind the successful execution of the DAY() function in a query, yet encountering an error when trying to insert

The current MySQL version is 8.0.23 Let's create a table and insert some data CREATE TABLE example1 (column1 varchar(10)); CREATE TABLE example2 (column1 varchar(10)); INSERT INTO example1 SELECT '20210818'; INSERT INTO example1 SELECT &ap ...

Tips for displaying dynamic data using innerHTML

Recently, I set out to implement an infinite scroll feature in Angular 2 using JavaScript code (even though it may seem a bit unusual to use JavaScript for this purpose, it's actually working perfectly). Initially, I was able to create an infinitely s ...

Trigger refetchQueries post-execution of a mutation operation

In the past, I executed a mutation in a similar manner as shown below: export const useEditLocationName = () => { const [editFavoriteLocationName] = useEditFavoriteLocationNameMutation({ refetchQueries: [{ query: GetMyFavouritePlacesDocument}], ...

Serverless Functions in ZEIT Now - Customizing Routes with Parameters

I successfully implemented 4 serverless routes /api/list (GET) /api/add (POST) /api/update/:id (PUT) /api/remove/:id (DELETE) These routes were added to the api/now.json file in the following format: {"src": "/api/list", "dest": "./list.js", "methods": ...

Creating a string-based template that can be included in Django

I need to create a list of clickable links for my navigation bar with the URLs provided using the url-tag. To achieve this, I have a list of dictionaries containing all the necessary information for each link, and I am creating a template string with them ...

Creating a callback in C code with Emscripten for JavaScript integration

In this challenge, the goal is to incorporate a JavaScript function as a callback to display progress during a while-loop operation. For example: var my_js_fn = function(curstate, maxstate){//int variables console.log(curstate.toString() + " of " + maxsta ...

What is the JavaScript event object all about?

Can you provide an example of what is considered an 'event object' in the context of this program? Is it, for instance, the <p> element if a <p> is clicked, or the <html> element if <html> is clicked? Or is the event objec ...

Is there a way to remove the arrow icons only from the beginning and end of a single <th></th> table cell?

Is it possible to remove the pseudo CSS class (before and after) from the first <th>#</th> tag in a table that uses Bootstrap and the responsive Datatable plugin? If so, can it be achieved using maybe JavaScript --> jQuery? Refer to this im ...

JavaScript issue causing input fields to malfunction and clear text boxes

I apologize for the simplicity of this question, but I am struggling with an issue and seeking help. Here's the problem: my calculate() method is not clearing text input as expected when testing my page. Below is the HTML markup and script: <!DOC ...

Discovering the worth of a key within a JSON file

Below is a JSON with objects containing artist and image values. I need a function that, given an artist name, will return the corresponding image value in the same object. All objects are enclosed in an array as a JSON. var iTunes_data = $([{ "titl ...

Achieving space between elements using Flexbox with a line separating each row

I have already found a solution to this question, but I am interested in exploring better alternatives. My goal is to utilize flexbox to create rows of items with equal spacing and dividing lines between them. The examples provided in the code snippet achi ...

Exploring the benefits of refactoring jQuery promises in use cases

I've been thinking about how to optimize this pseudo-code: function foo() { if (condition) { return somethingReturningPromise().then(function (data) { doSomethingOnSuccess(data); return mainFunctionReturningPromise(); // he ...

Utilizing multiple interactive dialog boxes with content pulled from JSON source

Welcome to the Mission Control Panel! On this interactive map, you can view mission markers and access detailed information for each mission by clicking on buttons inside the popups. Everything is dynamically generated from JSON data, so there are multiple ...

Instructions for concealing and revealing a label and its corresponding field before and after making a choice from a dropdown menu

Currently, I am working on developing a form that will enable customers to input their order information. This form includes a selection list for payment methods, with three available options. If the user chooses either credit or debit card as the paymen ...

What is the best way to retrieve attributes from a through table using a query?

I am in the process of creating a straightforward shopping cart system. My structure includes a Cart model, a Product model, and a connection table called CartItems. Here are the associations: models.Cart.belongsToMany(models.Product, { through: 'Car ...

Displaying information before it is fully loaded due to asynchronous calls

Having an issue where data from a JSON file is loading after a function has completed in JavaScript, causing it to not display properly in the browser. I've been researching alternative solutions through this stackoverflow post which offers some worka ...

SQL Check if resource is accessible during specified time period

I am currently working on a coding project to create a system that allows users to book items. One of the requirements is that an item cannot be booked twice, so I need to utilize SQL to determine if an item is available for booking. The database I am usi ...

The .map() function seems to be missing some data when fetching from the database in a Node.js

I am currently tackling an exercise for a Bootcamp, and the function I am using is not yielding the desired outcome. The objective is to query the database with a first name or a part of a first name. While I can successfully execute the DB query and retri ...

Angular causes HTML Dropdown to vanish once a null value is assigned

In my scenario, I have two variables named power and mainPower. Both of these variables essentially represent the same concept, with mainPower storing an ID of type Long in the backend, while power contains all attributes of this data transfer object. The ...