Incorporating a dynamic HTML editing button to every new row in a table using JavaScript

My application features a form that allows users to dynamically add new rows to a table using JavaScript:

// Function to add a new account row
if (tit.innerHTML === "Add Account"){
  var table = document.getElementById(tableId);
  var row = table.insertRow(0);
  var cell1 = row.insertCell(0);
  var cell2 = row.insertCell(1);

  cell1.innerHTML = document.getElementById("modal_type").value;
  cell2.innerHTML = document.getElementById("modal_price").value;

}

In addition to adding new rows, I am trying to include an edit button in each newly created row with a specified "td" class.

<td class=edtbutton><button class="edit_account" data-modal-target="#modal" id="editaccounts" onclick="sayedit()">✎</button></td>

I attempted to declare a variable called cell3 and insert the button code into it using cell3.innerHTML, but this did not work. Additionally, I tried concatenating the strings with += but encountered similar issues.

Answer №1

To streamline the process, I would set up a template cell and then duplicate it for each row that requires the specified class. For rows without the class, an empty cell can be added instead (alternatively, the last cell in the row could have its colspan expanded to accommodate those without an edit button). Here's an example:

function addButtons() {
  let cell = document.createElement('td');
  cell.classList.add('edtbutton');
  cell.innerHTML = '<button class="edit_account" data-modal-target="#modal" id="editaccounts" onclick="sayedit()">✎</button>';
  document.querySelectorAll('#t0 tr').forEach(row => {
    if (row.classList.contains('editableRow')) {
      row.appendChild(cell.cloneNode(true));
    } else {
      row.appendChild(document.createElement('td'));
    }
  });
}

function sayedit(){
  console.log('edit me…');
}
table {
  border-collapse: collapse;
  border-left: 1px solid #bbbbbb;
  border-top: 1px solid #bbbbbb;
}
tr.editableRow {
  background-color: #dddddd;
}
td {
  border-right: 1px solid #bbbbbb;
  border-bottom: 1px solid #bbbbbb;
}
<table id="t0">
  <tr><td>not editable
  <tr class="editableRow"><td>cell
  <tr class="editableRow"><td>cell
  <tr class="editableRow"><td>cell
</table>

<button onclick="addButtons()">Add buttons</button>

Answer №2

If you're looking to achieve a similar result, you might consider the following approach:

Start by defining the following function:

let createFragment = function (htmlString) {
  return document.createRange().createContextualFragment(htmlString);
}

After that, make use of it in the following manner:

if (title.textContent === "Create Account"){
          let table = document.getElementById(tableId);
          let row = table.insertRow(0);
          let cell1 = row.insertCell(0);
          let cell2 = row.insertCell(1);
          let cell3 = row.insertCell(2);
  cell1.innerHTML = document.getElementById("modalType").value;
  cell2.innerHTML = document.getElementById("modalPrice").value;
  let buttonHtml = '<td class="editButton"><button class="editAccount" data-modal-target="#modal" id="editAccounts" onclick="executeEdit()">✎</button></td>'
  cell3.appendChild(createFragment(buttonHtml));
}

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

Could you explain the contrast among "yarn serve," "yarn start," and "yarn build"?

Although both "yarn serve" and "yarn start" can launch my Vue project, I'm unsure of the differences between them. I've heard that "yarn build" is for packaging, but why don't I use it at work? Usually, I just upload my code to git and let ...

What is the best way in Javascript to retrieve and process multiple stream chunks from a single API request using the fetch() method

I'm dealing with a Node/Express backend where there is a lengthy (10 - 15sec) API call that is responsible for setting up a user's account. To initiate this action from the front-end, I simply use a fetch('my/api/url') GET request. My ...

Refresh the HTML content within a specified div element

In my index.html, there is a graph (created using d3.js) along with some code that displays a stepper with a number of steps equal to the child nodes of the clicked node: <div ng-include="ctrl.numlab==2 && 'views/stepper-two-labs.htm ...

Utilize HTML, AJAX, and JavaScript to retrieve the location of the current user and display markers for other users on a

I am attempting to display on a single map the current location of a user and markers for other users, whose locations are obtained through an ajax post. In essence, I am looking to merge the concepts from: Google Maps Geolocation Example with: Multiple ...

Node.js scheduler library for triggering events based on time in a cron-like fashion

Currently, I am utilizing Node.js to develop a web application. My aim is to trigger events at specific times. While I am aware of using setTimeout and computing the time difference from the present moment, this method does not account for various timezone ...

Creating a curved exponential data set with specific endpoints and a set number of data points

Struggling to create a function that involves math skills, I could really use some assistance. The task is to design a function that takes data points x and generates an array of size x with exponentially increasing values from 0 to 100. It would be ideal ...

The Challenge of Iterating Through an Array of Objects in Angular Components using TypeScript

Could someone please explain why I am unable to iterate through this array? Initially, everything seems to be working fine in the ngOnInit. I have an array that is successfully displayed in the template. However, when checking in ngAfterViewInit, the conso ...

tips for setting the value of a checkbox to true in React Material-UI with the help of React Hooks

<FormControlLabel onChange={handleCurrentProjectChange} value="end" control={<Checkbox style={{ color: "#C8102E" }} />} label={ <Typography style={{ fontSize: 15 }}> C ...

Strategies for integrating a username-only login using Firebase without requiring a password or email address

For my class assignment, I'm developing a webapp and want to implement a login system with only a username. However, when I try sending just the username to the database, it gets stored as a child under the connection ID in Firebase. Below is the Java ...

Issue with multi-level bootstrap navbar: Unable to hover on child elements

Currently, I am working on implementing a multi-level navbar in my project using Bootstrap Navbar along with additional CSS and Jquery. If you want to review the codes, they can be found at: CodePen $(function() { // ------------------------------- ...

What is the best way to display an image along with a description using Firebase and next.js?

I am currently utilizing Firebase 9 and Next.js 13 to develop a CRUD application. I am facing an issue where the images associated with a post are not correctly linked to the post ID. Furthermore, I need guidance on how to display these images in other com ...

Utilizing a Buefy element without Vue.js integration

Is there a way to generate a Buefy notification without utilizing a Vue component? Specifically, I'm attempting to implement a Buefy notification within the axios interceptor below: import axios from "axios"; import { Notification } from "buefy/dist/ ...

Activate a spinner when a button is clicked within a row of an antd table

I created a table with a column that includes a button like the one below: const columns = [ ... { title: "button", dataIndex: "key", render: (text, record) => { return ( <Button icon={<Del ...

Is it possible to verify whether a function contains a call to another function within it?

Consider a scenario in which we have the following nested functions: function function1(n) { function function2() { function function3() { function function4() { return n * 2; } return function4() } return ...

How about representing a two-dimensional array in a point-free manner?

Exploring functional/tacit style programming, specifically implementing the snake game (example: ) The main issue at hand involves processing an array of strings like: [ ['2 '], ['10'] ] and obtaining a list of coordinates in numer ...

Reveal or Conceal Information Depending on Cookie Status

Below is the Jquery code I am using: $("#tool").click(function() { $(".chelp").slideToggle(); $("wrapper").animate({ opacity: 1.0 },200).slideToggle(200, function() { $("#tool img").toggle(); }); }); When the #tool img is clicked, bot ...

Instructions on inserting a new row beneath a selected row using jQuery

https://i.stack.imgur.com/AlwHm.png When the second column is clicked, the method below is called: function getListOfList(primaryId, isFlat, col) { alert(primaryId) $.ajax({ url : ("/" + serverURL + "/dataGrid/getChilds"), ...

Navigate to a PDF file from an HTML5 application using PhoneGap by accessing an external link

Can anyone help me figure out what I'm doing wrong here? Essentially, I am trying to open a PDF in Google Viewer: <a id="pdflink" href="https://docs.google.com/viewer?url=http://pdpdpd.pdf" target="_blank">Pdf</a> When it opens in the vi ...

Fixing TypeError in React App: How to Resolve the "Cannot read property 'prototype' of undefined" Issue

I am completely new to JavaScript and I am struggling to understand the error that keeps popping up. After doing some research, it seems like the error could be due to a poorly written function or something along those lines. Here are the classes involved ...

renewing a div element without the need to reload the entire webpage

I'm currently developing a setup process for configuring a database. My goal is to allow the user to progress through each phase without having to refresh the page. However, I've encountered an issue while trying to implement the .load() function ...