Add a new row to a table using auto increment feature in Javascript

I am having issues with inserting rows using a button in Javascript. When I click the button, rows are being inserted unexpectedly as shown in the images below. Additionally, I also need a delete row button to work in a similar manner. Thank you for any help.

Click here to view table image

Here is my code:

<style>
    table {
        border-collapse: collapse;
        margin: 100px;
    }

    table, td, th {
        border: 1px solid black;
        padding: 10px;
    }
</style>

<table id="t1">
    <tr>
        <th>Task No</th>
        <th>Done/In Progress</th>
        <th>Deadline</th>
        <th>Task</th>
    </tr>

    <tr>
        <td>1.</td>
        <td>
            <input type="checkbox" />
        </td>
        <td></td>
        <td>
            <input type="text" style="width:100%;" />
        </td>
    </tr>
</table>

<input style="margin-top:-200px; padding:10px" type="button" value="Add Row" onclick="add()" />

Javascript:

<script>
    function add() {
        var num = document.getElementById("t1").rows.length;
        console.log(num);
        var x = document.createElement("tr");

        var a = document.createElement("td");
        var anode = document.createTextNode(num);
        a.appendChild(anode);
        x.appendChild(a);

        a = document.createElement("td");
        anode = document.createElement("input");
        var b = document.createAttribute("type");
        b.value = "checkbox";
        anode.setAttributeNode(b);
        a.appendChild(anode);
        x.appendChild(a);

        a = document.createElement("td");
        anode = document.createElement("input");
        b = document.createAttribute("type");
        b.value = "text";
        anode.setAttributeNode(b);
        a.appendChild(anode);
        x.appendChild(a);
        document.getElementById("t1").appendChild(x);
    }
</script>

Answer №1

Do you need assistance with this particular query? I recommend trying out this resource: click here to access the jsbin link

function insert() {
    var count = document.getElementById("table").rows.length;
    console.log(count);
    var newRow = document.createElement("tr");

    var cellA = document.createElement("td");
    var textNode = document.createTextNode(count+'.');
    cellA.appendChild(textNode);
    newRow.appendChild(cellA);

    cellA = document.createElement("td");
    textNode = document.createElement("input");
    var attrib = document.createAttribute("type");
    attrib.value = "checkbox";
    textNode.setAttributeNode(attrib);
    cellA.appendChild(textNode);
    newRow.appendChild(cellA);
  
    cellA = document.createElement("td");
    newRow.appendChild(cellA);

    cellA = document.createElement("td");
    textNode = document.createElement("input");
    attrib = document.createAttribute("type");
    attrib.value = "text";
    textNode.setAttributeNode(attrib);
    cellA.appendChild(textNode);
    newRow.appendChild(cellA);
    
    cellA = document.createElement("td");
    textNode = document.createElement('input');
    textNode.setAttribute('type','button');
    textNode.setAttribute('value','Remove Row');
  textNode.setAttribute('onclick','deleteRow(this)');
    cellA.appendChild(textNode);
    newRow.appendChild(cellA);
    document.getElementById("table").appendChild(newRow);
}

function deleteRow(element,val) {
  var tableRow = element.parentElement.parentElement;
  var table = element.parentElement.parentElement.parentElement;
  table.removeChild(tableRow);

}
table {
    border-collapse: collapse;
    margin: 100px;
}

table, td, th {
    border: 1px solid black;
    padding: 10px;
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
  
  <table id="table">
<tr>
    <th>Task Number</th>
    <th>Completed/In Progress</th>
    <th>Due Date</th>
    <th>Task Description</th>
    <th><input style="margin-top:-200px; padding:10px" type="button" value="Add Row" onclick="insert()" /></th>
</tr>

<tr>
    <td>1.</td>
    <td>
        <input type="checkbox" />
    </td>
    <td></td>
    <td>
        <input type="text" />
    </td>
  <td> <input type="button" value="Delete Row" onclick="deleteRow(this)" /></td>
    
</tr>
  </table>


</body>
</html>

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

What is the process for inserting an image into a table using el-table and el-table-column components in Vue.js while utilizing ui-elements?

I'm new to Vue.js and successfully built a basic table using the ui-element. The el-table element was utilized for constructing the table, with columns displayed using el-table-column and prop (see code below). Now, I want to incorporate images/avatar ...

checkbox causing the button to appear empty

Due to the inability of a ngIf and ngFor to coexist, I added an ng-container to facilitate the loop. However, after making this change, nothing seems to be working as expected without any clear reason. Below is the code snippet that is causing trouble: Vi ...

Discovering all the links present on a webpage using node.js

Currently, I am diving into node.js (webdriver) and encountering some challenges. Despite my efforts to search online for examples of the tasks I need help with, I have come up empty-handed. One example that has me stumped is how to log all links from a pa ...

Promise.allSettled() - Improving resilience through retry mechanisms for concurrent asynchronous requests

TL;DR: I'm seeking advice on how to handle multiple promise rejections and retry them a specified number of times when using Promise.allSettled() for various asynchronous calls. Having come across this article: I was intrigued by the following state ...

Updating $scope from another controller in AngularJS

I am facing an issue where I need to update the $scope inside a directive's link function. Here is what my controller and directive look like: $scope.current = 0; angular.module('myAPP') .directive('post', function() { ...

Unable to eliminate the overlapping box-shadow

Specifically, I am utilizing polymer paper-shadow for my project. I am attempting to eliminate two sides of a paper-shadow box in order to create a basic arrow box, but I am facing difficulties in achieving this. Removing the position: absolute did not re ...

What is the proper way to place a newly added element using absolute positioning?

Currently, I am in the process of developing a tooltip feature. This function involves adding a div with tooltip text inside it to the element that is clicked. However, I am facing a challenge in positioning this element above the clicked element every tim ...

Applying various Angular filters to an array of objects within HTML select elements

I'm fairly new to working with JS and the rather challenging learning curve of AngularJS. I have an array containing numerous objects with the relevant properties listed below: $scope.myRecs = [{country: 'Ireland', city: 'Dublin&apos ...

Angular tutorial: Organizing data by date only

This is my first time building an Angular app. I am fetching JSON data from an API using a factory service to get football match fixtures. My goal is to group these fixtures by date while disregarding the time component. The date string in the JSON is fo ...

Leveraging Java jsoup for extracting information from an HTML page and saving the data

Attempting to utilize the jsoup libraries for parsing an HTML file and extracting all data associated with table class="scl_list", a segment within the larger HTML document. <table class="scl_list"> <tr> <th align="cente ...

Move the material ui menu to the far left side of the page

How can I adjust the menu to align with the left side of the page without any gaps? I've tried various methods but it's not moving to the left. Any suggestions? https://i.sstatic.net/jcAes.jpg Here is the relevant code snippet: <Menu ...

"How to retrieve the height of an element within a flexslider component

I need some assistance with using JavaScript to determine the height of an element within a flexslider. There are two challenges I am facing. When I attempt to use a regular function getHeight(){ var h = document.getElementById("id-height").style.height; ...

Is it beneficial to utilize jQuery ahead of the script inclusions?

While working on a PHP project, I encountered a situation where some parts of the code were implemented by others. All JavaScript scripts are loaded in a file called footer, which indicates the end of the HTML content. This presents a challenge when tryi ...

How can you master the art of PHP templating like a pro?

Years ago, I started a small PHP website that has since grown into quite a mess. Despite having a separate template for the final HTML output, I still find myself handling a lot of HTML within the 'business logic' part of the code. My main issue ...

What steps are necessary for TypeScript to retrieve my definitions when utilizing node.js require statements?

I have been utilizing Visual Studio 2013 tools for Node.js along with VS2013 Update 2. In my util.ts file, I have the following code: var Util = function () { this.getSelectOption = function (elem, value) { var x = 99; } module.exports = ...

Utilize Vuex store in Vue without the need for import statements within components

When working with Vue 2/3 and in an ES6 environment, I often access a Vuex store in an external JS file using the following method: // example.js import { store } from '../store/index'; console.log(store.state.currentUser); While this method w ...

How can I stack a div on top of two columns in Bootstrap?

My goal is to design something like this: I want to have a single-color strip that extends over three columns: https://i.sstatic.net/1XfAu.png What I am aiming for is a layout where the grey line overlaps columns 2 and 3. /* added by editor for demo p ...

How to insert an element INTO a JSON array using JavaScript

I'm having an issue with the way a line is displayed on my screen: Would you like to pay €xx to POS_ID Latte X 1....€2.50-Salad X 1....€4.00-Wrap X 1....€4.50-Coffee X 2....€3.00- My desired format is as follows: Would you like to pay ...

Click on the input field to give it focus before adding a class during the page

Alright, so here's the deal - I have an input field with the class .cf-se-input. I want this field to be focused using jQuery as soon as the document is ready. Additionally, if the field is focused either by the user clicking on it or through jQuery f ...

Creating TypeScript models from a JSON response in React components

My Angular 2 application retrieves a JSON string, and I am looking to map its values to a model. According to my understanding, a TypeScript model file is used to assist in mapping an HTTP Get response to an object - in this case, a class named 'Custo ...