Creating interactive tables in JavaScript with dynamic row adding, editing and deleting capabilities

Whenever I try to add a new row by clicking the Add Row button, an error occurs. My goal is to append a new 'tr' every time I click the add row button. Each 'td' should include a checkbox, first name, last name, email, mobile number, edit, and save buttons.

  1. I want to be able to save the values when I click the save button.
  2. There should also be an edit button to modify the fields.
  3. The checkbox is for selecting multiple rows in order to delete them all at once.

Could someone please assist me with this? Thank you in advance.

var form = document.createElement('form');
document.body.appendChild(form);

var table = document.createElement('table');
table.setAttribute("id","myTable");
form.appendChild(table);

var btnClick = document.createElement('button');
btnClick.setAttribute('onclick','addTable()');
btnClick.innerHTML = "Add Row";
form.appendChild(btnClick);

var btnSave = document.createElement('button');
btnSave.innerHTML = "Save";

var btnDelete = document.createElement('button');
btnDelete.innerHTML = "Delete";

var btnEdit = document.createElement('button');
btnEdit.innerHTML = "Edit";

var checkbox = document.createElement('input');
checkbox.type = "checkbox";

var input = document.createElement('input');
input.type = "text";
input.placeholder = "Firstname";

var input1 = document.createElement('input');
input1.type = "text";
input1.placeholder = "Lastname";

var input2 = document.createElement('input');
input2.type = "email";
input2.placeholder = "Email";

var input3 = document.createElement('input');
input3.type = "number";
input3.placeholder = "Number";

function addTable() {
  var row = document.createElement('tr');
  table.appendChild(row);  
  var cell = document.createElement('td');  
  row.appendChild(cell);
  cell.appendChild(checkbox);
  cell.appendChild(input);
  cell.appendChild(input1);
  cell.appendChild(input2);
  cell.appendChild(input3);
  cell.appendChild(btnSave);
  cell.appendChild(btnEdit);
}

JsFiddle

Answer №1

One key adjustment to make is changing the tag used for the add row button on your form. Opting for a button will trigger form submission each time you click it, potentially undoing any added rows or other page modifications. Consider using an < input > tag with type button for the same functionality. Similarly, consider applying this change to the save, edit, and delete buttons to enable page responsiveness without reloading.

You're almost set with everything else in your code. An alternative approach would be minimizing the use of setAttribute for all elements. Instead, directly set properties like id and onclick upon element creation (e.g., table.id = "myTable";). Save setAttribute for scenarios where multiple style properties need to be declared at once (e.g., table.setAttribute("style","border:2px solid;color:red;");).

Below is a revised version of your code that functions as intended:

window.onload = function(){
    var addTable = function() {
        var checkbox = document.createElement('input');
        checkbox.type = "checkbox";

        var input = document.createElement('input');
        input.type = "text";
        input.placeholder = "Firstname";

        var input1 = document.createElement('input');
        input1.type = "text";
        input1.placeholder = "Lastname";

        var input2 = document.createElement('input');
        input2.type = "email";
        input2.placeholder = "Email";

        var input3 = document.createElement('input');
        input3.type = "number";
        input3.placeholder = "Number";

        var btnSave = document.createElement('button');
        btnSave.innerHTML = "Save";

        var btnDelete = document.createElement('button');
        btnDelete.innerHTML = "Delete";

        var btnEdit = document.createElement('button');
        btnEdit.innerHTML = "Edit";

        var row = document.createElement('tr');
        table.appendChild(row);  
        addCell(row,checkbox);
        addCell(row,input);
        addCell(row,input1);
        addCell(row,input2);
        addCell(row,input3);
        addCell(row,btnSave);
        addCell(row,btnEdit);
        addCell(row,btnDelete);
      };

      var form = document.createElement('form');
      form.method = "post";
      document.body.appendChild(form);

      var table = document.createElement('table');
      table.id = "myTable";
      form.appendChild(table);

      var btnClick = document.createElement('input');
      btnClick.type = "button";
      btnClick.value = "Add Row";
      btnClick.onclick = addTable;
      form.appendChild(btnClick);
  };

  function addCell(row,elm){
      var cell = document.createElement('td');  
      row.appendChild(cell);
      cell.appendChild(elm);
  }

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

Embedding a label's text directly as HTML code in an ASP.NET page

I attempted this CABC</td><td valign="top"><span class="progressBar pb3">document.getElementById('<%#Label8.ClientID%>').innerHTML</span></td></tr> I am trying to incorporate a jQuery script for a sales ...

Retrieve a particular HTML element from an object that has been mapped

After reproducing my issue on a smaller scale for easier handling, I am now aiming to implement an onclick function that reveals the hidden content inside each column. The plan is to initially hide the content using display: none and then switch it to disp ...

Determine whether the object is facing the specified position

I'm attempting to verify whether an object (this.target) is facing towards a particular position (newPosition). Here's what I currently have: new THREE.Matrix4().lookAt( newPosition, this.target.position, this.target.up ) == this.target.matrix ...

Is it possible to customize the background color of select2 boxes separately for each option?

I recently implemented the select2 plugin and now I'm looking to add a new class within the .select2-results .select2-highlighted class in order to change the background color. Does anyone have any suggestions on how to achieve this? ...

Ways to convert a callback-based function into a promise without losing the returned value

After being given access to this API: function doSomeWork(callbacks : { success ?: (result : SuccessCallbackResult) => void, fail ?: (result : FailCallbackResult) => void, complete ?: (result : CompleteCallbackResult) => void }) : Task ...

What methods are most effective for evaluating the properties you send to offspring elements?

Currently, I'm in the process of testing a component using Vue test utils and Jest. I'm curious about the most effective method to verify that the correct values are being passed to child components through their props. Specifically, I want to e ...

One way to filter using a single array

Currently testing some angularJS with this particular example http://www.w3schools.com/angular/tryit.asp?filename=try_ng_filters_filter <ul> <li ng-repeat="x in names | filter : 'i'"> {{ x }} </li> </ul> Is ther ...

Transferring data between nested IFrames and triggering a page refresh

Looking for a way to pass multiple values between two embedded IFRAMES and refresh the receiving iframe src. Is there any solution you recommend, specifically in c# code behind file (asp.net)? Welcome any ideas and suggestions. Thank you. ...

Adding an item to a sleek carousel

Adding items to a Slick carousel in a vue.js demo is proving to be a bit tricky. When I try to use the refresh() function after adding an item, it doesn't seem to work as expected even though the item is successfully added with vue.js. //Attempting to ...

Difficulty encountered while implementing the if-else statement in raycasting operations

Currently, I am experimenting with raycasting to determine if my mouse is pointing at an object. The function seems to be working fine when the object is not being touched - it correctly prints out "didnt touch". However, when the object is touched, it s ...

Encountered an error while attempting to access the 'type' property of undefined within the Redux store for an action defined in an external package

In my quest to expand my knowledge of React (coming from an ASP.NET background), I encountered a challenge. I have multiple React applications where I intend to utilize common UI components, so I decided to extract these into a separate npm package. This a ...

Is your Node.js HTTP Request failing to function properly?

I am currently working on creating an HTTP Request function where all requests are directed to the same domain but with different file names. Unfortunately, I am encountering a problem where nothing is being displayed in the console and no data is being r ...

"Experience the power of Vue.js 3 and vue-router as the @click event seamlessly refreshes the entire

Just getting started with Vue and I'm trying to figure out how to toggle the menu open/close on mobile navigation without causing the whole page to reload. Any suggestions on how to prevent that? Here's my code: <router-link to="/ " @click="t ...

Why are the values in my options created using the array map method empty in React?

I decided to use a for loop to generate an array containing the numbers 1 through 12 representing each month. I then attempted to utilize the map array method to create 12 options, but unfortunately they are coming up empty. Below is a snippet of the ...

What is the correct way to send parameters in the action tag?

Can I set the res variable as the form action in HTML? <script> var name =$("#name").val(); var file =$("#file").val(); var res= localhost:8080 + "/test/reg?&name="+name+"&file=" +file ; </script> <form acti ...

Detecting URL changes, excluding just the hash, with JavaScript/jQuery

It's interesting to note that some websites are built using a "one-page system". In this type of system, when a user clicks on a link, the site doesn't take them to a new page but instead reloads the existing page with Ajax and updates the URL. ...

I am facing an issue with the clearTimeout function in my JavaScript code. Can anyone help

I am encountering some issues with the clearTimeout() function. The setTimeout() function is working as expected, but I want it to stop running when I close my notification. I'm not sure what is causing the problem in my function. After closing the ...

Angular JS: Distribute objects from a single array to various arrays or services

I have recently embarked on developing a basic app using Angular JS, utilizing a service/factory to manage data and enable the addition of objects. Within the array of various individuals (listed in the html), you can include them as candidates by employi ...

Is there a way to adjust the size of the canvas element in HTML without compromising quality or resorting to zooming?

I'm currently working on a basic modeling application for the web. The main component of my app is a canvas element that I'm trying to size correctly. However, when I set the height and width using CSS, it scales the entire canvas and compromises ...

Guide to resolving a blank webpage issue post running 'npm run build'

I am currently in the process of working on a project that involves Vue and Firebase. Unfortunately, I have encountered an issue where my development server is no longer rendering new routes from my Vue router after building and deploying to production. F ...