How to convert a modal popup text editor into a regular input box when dynamically adding rows with jQuery

I've successfully implemented a dynamic data table, but I'm facing a small issue with the Second row in the "NARRATION" column.

The problem arises when I click on the "ADD NEW" button to add a new row. The narration column in the second row displays a popup text editor, which is working fine. However, when I add another row by clicking "ADD NEW" again, the narration column also shows the popup text editor, which is not desired.

My goal is to change the input method in the dynamically added rows to a normal input box instead of a modal text editor that appears for the first two rows.

Specifically, I want only the first two rows to display the popup text editor, while any additional rows should have input boxes.

Access the full code here on FIDDLE

/* TABLE JS */

$(document).ready(function() {
  // JavaScript code for handling dynamic rows goes here
});

/* POPUP JS */
// JavaScript code for handling popups and their functionalities goes here
<!-- Add necessary external libraries -->

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
</head>
<body>

<!-- Your table markup and modal popups go here -->

</body>
</html>

Full code available on FIDDLE

I hope this question makes sense now.

Answer №1

Your issue has been identified and a solution has been provided in the following code snippet:

Updated JavaScript Code:

/* Updated Table JS */

$(document).ready(function() {
  $("#update_button").on("click", function() {
    // Dynamic Rows Update Code

    // Calculate maximum row id and assign new id
    var newid = 0;
    $.each($("#data_table tr"), function() {
      if (parseInt($(this).attr("data-id")) > newid) {
        newid = parseInt($(this).attr("data-id"));
      }
    });
    newid++;

    var tr = $("<tr></tr>", {
      'id': "row" + newid,
      'data-id': newid
    });

    // Iterate through each table data cell to create new elements with updated names
    $.each($("#data_table tbody tr:nth(1) td"), function() {
      var td;
      var cur_td = $(this);

      var children = cur_td.children();

      // Create new table data cell with updated name if available
      if ($(this).attr("data-name") !== undefined) {
        td = $("<td></td>", {
          'data-name': $(cur_td).attr("data-name")
        });

        var c = $(cur_td).find($(children[0]).prop('tagName')).clone().val("");
        c.attr("name", $(cur_td).attr("data-name") + newid);
        c.appendTo($(td));
        td.appendTo($(tr));
      } else {
        td = $("<td></td>", {
          'text': $('#data_table tr').length
        }).appendTo($(tr));
      }
    });

    // Append the updated row to the table
    $(tr).appendTo($('#data_table'));

    $(tr).find("td button.row-update").on("click", function() {
      $(this).closest("tr").remove();
    });
  });

  // Implementation of Sortable Feature
  var fixHelperModified = function(e, tr) {
    var $originals = tr.children();
    var $helper = tr.clone();

    $helper.children().each(function(index) {
      $(this).width($originals.eq(index).width())
    });

    return $helper;
  };

  $(".sortable-table tbody").sortable({
    helper: fixHelperModified
  }).disableSelection();
  $(".sortable-table thead").disableSelection();
  $("#update_button").trigger("click");
});

/* Additional Popup Functionality */
$('.info_btn').on('click', function() {
  let value = $('.userInput').val();
  $('#description_field').val(value);
});

$('.delete_btn').on('click', function() {
  let value = $('.confirmDelete').val();
  $(".confirmDelete").val("");
  $('.selected').val(value);
  $(".selected").removeClass("selected");
})

$(document).on('click',"input#item_description", function() {
  $(".selected").removeClass("selected");
  $(".confirmDelete").val( $(this).val() );
  $(this).addClass("selected");
})

Answer №2

Hello, I have solved your issue by updating your fiddle.

All you need to do is remove the data-toggle and data-target properties from the newly created row because they are being cloned along with the elements.

$("#"+trId +" #acc_narrat").removeAttr("data-target")
$("#"+trId +" #acc_narrat").removeAttr("data-toggle")

You can see the working example here

Answer №3

To clone a row and modify its ids, you must ensure to delete the data-target="#narratModal" attribute from the input box to prevent the modal from appearing. Simply locate the input box and remove the data-target="#narratModal" attribute as shown in the code snippet below:

/* TABLE JS */

$(document).ready(function() {
  $("#add_row").on("click", function() {
    // Dynamic Rows Code

    // Get max row id and set new id
    var newid = 0;
    $.each($("#tab_logic tr"), function() {
      if (parseInt($(this).data("id")) > newid) {
        newid = parseInt($(this).data("id"));
      }
    });
    newid++;

    var tr = $("<tr></tr>", {
      id: "addr" + newid,
      "data-id": newid
    });

    // loop through each td and create new elements with name of newid
    $.each($("#tab_logic tbody tr:nth(1) td"), function() {
      var td;
      var cur_td = $(this);

      var children = cur_td.children();

      // add new td and element if it has a nane
      if ($(this).data("name") !== undefined) {
        td = $("<td></td>", {
          "data-name": $(cur_td).data("name")
        });

        var c = $(cur_td).find($(children[0]).prop('tagName')).clone().val("");
        c.attr("name", $(cur_td).data("name") + newid);
        c.appendTo($(td));
        td.appendTo($(tr));
      } else {
        td = $("<td></td>", {
          'text': $('#tab_logic tr').length
        }).appendTo($(tr));
      }
    });

    // add the new row
    $(tr).appendTo($('#tab_logic'));

    $(tr).find("td button.row-remove").on("click", function() {
      $(this).closest("tr").remove();
    });
    // remove data-target so that popup will not be shown
     $(tr).find('input[name^=narrat]').removeAttr('data-target');
  });

  // Sortable Code
  var fixHelperModified = function(e, tr) {
    var $originals = tr.children();
    var $helper = tr.clone();

    $helper.children().each(function(index) {
      $(this).width($originals.eq(index).width())
    });

    return $helper;
  };

 ...
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>

...
</table>
</div>


<a class="btn btn-primary float-right adRow" id="add_row">Add New</a>

...

Answer №4

To properly replicate your td elements, you need to clone them and delete the data-target attribute from the input field.

Below is the modified element loop:

// iterate through each td and generate new elements with the name of newid
$.each($("#tab_logic tbody tr:nth(1) td"), function() {
  var td;
  var cur_td = $(this).clone();  

  var children = cur_td.children();
  $(cur_td).find('#acc_narrat').removeAttr('data-toggle'); 

  // create new td and element if it has a nane
  if ($(this).data("name") !== undefined) {
    td = $("<td></td>", {
      "data-name": $(cur_td).data("name")
    });

    var c = $(cur_td).find($(children[0]).prop('tagName')).clone().val("");
    c.attr("name", $(cur_td).data("name") + newid);
    c.appendTo($(td));
    td.appendTo($(tr));
  } else {
    td = $("<td></td>", {
      'text': $('#tab_logic tr').length
    }).appendTo($(tr));
  }
});

In essence, you must clone the columns by using var cur_td = $(this).clone(); to sever ties with the original elements. Additionally, remove any connection to the modal from the element using

$(cur_td).find('#acc_narrat').removeAttr('data-toggle');

You can view the updated version on this fiddle link.

Answer №5

Strategically eliminate the data-toggle attribute from the TD elements prior to adding them to $('#tab_logic')

/* JavaScript for Table */

$(document).ready(function() {
  // Event handler for adding new rows
  $("#add_row").on("click", function() {

    var newid = 0;
    $.each($("#tab_logic tr"), function() {
      if (parseInt($(this).data("id")) > newid) {
        newid = parseInt($(this).data("id"));
      }
    });
    newid++;

    var tr = $("<tr></tr>", {
      id: "addr" + newid,
      "data-id": newid
    });

    // loop through each td and create new elements with dynamic names
    $.each($("#tab_logic tbody tr:nth(1) td"), function() {
      var td;
      var cur_td = $(this);
      var children = cur_td.children();

      // add new td and element if it has a nane
      if ($(this).data("name") !== undefined) {
        td = $("<td></td>", {
          "data-name": $(cur_td).data("name")
        });
        var c = $(cur_td).find($(children[0]).prop('tagName')).clone().val("");
        c.attr("name", $(cur_td).data("name") + newid);
        c.appendTo($(td));
        td.appendTo($(tr));
      } else {
        td = $("<td></td>", {
          'text': $('#tab_logic tr').length
        }).appendTo($(tr));
      }
    });
    
    $(tr).find('#acc_narrat').removeAttr('data-toggle');

    // add the new row
    $(tr).appendTo($('#tab_logic'));

    $(tr).find("td button.row-remove").on("click", function() {
      $(this).closest("tr").remove();
    });
  });

  // Sortable Code
  var fixHelperModified = function(e, tr) {
    var $originals = tr.children();
    var $helper = tr.clone();

    $helper.children().each(function(index) {
      $(this).width($originals.eq(index).width())
    });

    return $helper;
  };

  $(".table-sortable tbody").sortable({
    helper: fixHelperModified
  }).disableSelection();
  $(".table-sortable thead").disableSelection();
  $("#add_row").trigger("click");
});

/* JavaScript for Popup */
$('.cashmodal_btn').on('click', function() {
  let val = $('.myInput').val();
  $('#pay_narrat').val(val)
});

$('.cashmodal_btn').on('click', function() {
  let val = $('.acnarrate').val();
  $('#acc_narrat').val(val);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>

<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>


<!-- table -->

<a id="add_row" class="btn btn-primary float-right adRow">Add New</a>
<div class="col-md-12 table-responsive">
  <table class="table table-bordered table-hover table-sortable" id="tab_logic">
    <thead style="background-color: #680779;
                                                        color: #fff;">
      <tr>
       <!-- table headers go here -->
      </tr>
    </thead>
    <tbody>
      <!-- table rows go here -->
    </tbody>
  </table>
</div>

<!-- narration text popup modal -->

<!-- Modals for narration input -->

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

Encountering a TypeError while trying to implement a dropdown button feature in Bootstrap 5

I'm attempting to implement a Dropdown button using Bootstrap 5, but encountering an error: Uncaught TypeError: t.createPopper is not a function Here is the HTML code I am using: <div class="dropdown"> <a class="btn btn- ...

Display the item request form whenever a selection of an unidentified item is made using select2

I want to implement select2 for a company search feature. In case the desired company is not available in the existing dataset, I need to provide an option for users to request adding the company data. This is the HTML code: <head> <link href=& ...

Is there a way to disable the auto focus on the button in this message box/alert?

I am currently using Element UI's message box for alert notifications in a Vue application. While the functionality of this component is working fine, I have noticed that when the alert pops up, one of the buttons automatically receives focus. Please ...

Adding a class to an element can be easily achieved when both input fields have values

Is it possible to apply the "active" class to the element go_back_right only when both inputs with classes search_box_name and search_box_id have content in them? I've tried looking for solutions on this platform, but being new to JavaScript, I couldn ...

Is there a way for me to design a share or like button that website owners can easily incorporate into their sites, allowing their visitors to interact with my content and drive traffic

Is there a way I can incorporate a share or like button on my site to allow other website owners to use it, sending back data to my site similar to how social media platforms like Twitter and Digg operate? I'm seeking guidance on this topic - anyone ...

Bizarre Actions of a JavaScript Object

Currently, I am in the process of developing a Multiplayer game using Phaser and Eureca io. My main focus right now is on perfecting the authentication of players and their controls. To achieve this, I have implemented a method on the server that retrieves ...

Returning a React component only under certain conditions to meet the requirements of a Suspense fallback mechanism

Whenever I return a component (using nextjs 13) that depends on fetched data, I usually conditionally render elements to ensure that the values are available: TableComponent: export const Table = ({ ...props }) => { const [tableEvents, setTableEve ...

JavaScript Class vs Function as Definition

Having trouble locating documentation for this issue. I devised a JavaScript class in the following manner: class Polygon { constructor(height, width) { this.height = height; this.width = width; } area = function() { return this.height ...

What is the sequence in which Jest executes its tests?

A fascinating challenge I've taken on involves testing a card game created in JavaScript using Jest. Currently, I have developed two tests: one to verify the creation of a 52-card deck and another to confirm that the player is dealt two cards at the ...

Execute jQuery script only for a specific URL and not for another URL, even though both URLs have similar functionality

I need to run specific script only on but not on The script doesn't seem to be working as intended. var url = location.pathname; if (url.indexOf('Previsions') >= 0) { //insert script here } What should be the next step to resolve this ...

Persisting jQuery UI position in database and showing it on the screen

i am currently working on a project using jquery ui for resizing and drag and drop features. i need to figure out how to save these changes in a database. here is the progress i have made so far: http://plnkr.co/edit/rAwEs6eUS2JPmFMxqQ?p=preview i am look ...

Using code, you can implement this by utilizing the following URL: https://graph.facebook.com/ql?q=http://google.com

(PLEASE AVOID CLICKING NEGATIVE RATINGS. I REALLY NEED AN ANSWER TO THIS. THANK YOU) As a beginner in coding and learning, I am eager to edit the code on my website. The code/link https://graph.facebook.com/fql?q=http://google.com has already been depreca ...

Apply the jQuery method to select elements with index 3, 4, 5, 6, or 7, then add

My current Wordpress blog displays 20 posts. I am looking to apply a specific class to posts numbered 2 through 10, and then again from 12 to 20. I do not want the first post or post number 11 to have this class added. I attempted using CSS selectors lik ...

Is there a way to invoke a class method from the HTML that is specified within its constructor function?

class Welcome { constructor() { this.handlePress = this.handlePress.bind(this); this.htmlContent = `<a onclick="this.handlePress">Link</a>`; } handlePress(e) { console.log('planet'); } } The HTML structure appears ...

Mongooses do not clutter the array with unnecessary lines

I need help generating a sorted list from the database. Here is my current code: const subs = await Sub.find({}, {userName: 1, score: 1, _id: 0}).sort({ score: 'desc' }); The output I am getting looks like this: { userName: 'test1', ...

What is the best approach to eliminate an element from the array cart using JavaScript?

I currently have an array: [ 0: {title: "Banana", price: 1.00, count: 2}, 1: {title: "Taco", price: 3.99, count: 1}, 2: {title: "Burrito", price: 6.50, count: 1}, 3: {title: "Soda", price: 1.25, count: 1} ...

Using the jQuery/JavaScript operator is similar to the SQL LIKE query with the wildcard %

Is there a way to search for a specific part of my input using JavaScript/jQuery? I've tried two different methods, but neither yielded any results. <script type="text/javascript> $("#button").click(function () { $("#DivToToggle").toggle(); ...

Pressing the button will reveal the contents of .container3

If you require any additional information, please feel free to reach out. I find it quite puzzling why I am struggling to solve this. While I can successfully navigate from .container1 to .container2 using the first exit button, I'm facing difficult ...

Is it possible to write a text file in UTF-16 using Javascript?

I need to create a UTF-16 text file from a string. For instance: var s = "aosjdfkzlzkdoaslckjznx"; var file = "data:text/plain;base64," + btoa(s); The above code generates a UTF-8 encoding text file. How can I modify it to produce a UTF-16 text file usin ...

What is the best way to identify when the soft-keyboard is hidden in the Android browser

Having trouble with the Android Webkit browser and need to manually detect when the soft-keyboard is hidden by pressing the button in the top right corner. https://i.stack.imgur.com/x11Vp.jpg In the image above, pressing the button hides the soft keyboar ...