0

I am trying to add numbers before each table row when I add a new row through a form, so all the added rows are numbered. This is the code I use for adding rows, which works. Somebody knows hows to do add a new <td> to the table?

var btn = document.getElementById('btn');
btn.onclick = myFunction;

function myFunction() {
    validateForm()
    addRow()
}


function addRow() {
    //Get data from filled in form
    var form = document.getElementById('form');
    var newData = [];
    for(var i = 0; i < form.length; i++) {
        newData[i] = form.elements[i].value;
    }

    if(validateForm() == true) {
        //Put data in table
        var table = document.getElementById('table');
        var newRow = table.insertRow();

        for(var i = 0; i < 3; i++) {
        var newCell = newRow.insertCell(i);
        newCell.innerHTML = newData[i];
        }
    }

    form.reset();
}


function validateForm() {
    var f = document.getElementById('form');

    if(f.fname.value == '') {
        alert('Please fill in first name');
        return false;
    }
    if(f.lname.value == '') {
        alert('Please fill in last name');
        return false;
    }
    if(f.points.value == '') {
        alert('Please fill in points');
        return false;
    }
    if(isNaN(f.points.value)) {
        alert('Points should be a number')
        return false
    }

    return true;

}
2
  • Worth mentioning you might be able to number the rows with CSS counters, which save you writing more JavaScript: developer.mozilla.org/en-US/docs/Web/CSS/CSS_Lists_and_Counters/… Commented Apr 28, 2020 at 11:28
  • @odlp thank you, but I have to do this with javascript. Commented Apr 28, 2020 at 11:52

2 Answers 2

1

You can find the current number of rows in table and then add 1 to that and add it to new row.

You can find the number of rows in table by

const table = document.getElementById("myTable");
const numOfRows = table.getElementsByTagName('tr');
console.log(numOfRows.length);

Updated addRow() method will be

function addRow() {
    //Get data from filled in form
    var form = document.getElementById('form');
    var newData = [];
    for(var i = 0; i < form.length; i++) {
        newData[i] = form.elements[i].value;
    }

    if(validateForm() == true) {
        //Put data in table
        var table = document.getElementById('table');
        const rows = table.getElementsByTagName('tr');
        const currentRow = rows.length + 1;

        var newRow = table.insertRow();
        const firstCell = newRow.insertCell(0);
        firstCell.innerHTML = currentRow;
        for(var i = 1; i <= 3; i++) {
          var newCell = newRow.insertCell(i);
          newCell.innerHTML = newData[i];
        }
    }

    form.reset();
}

jsfiddle demo https://jsfiddle.net/m9rh1uvw/

Sign up to request clarification or add additional context in comments.

2 Comments

u beet me to it, was gona write up this, i like this answer more than the excepted once. also i would just have a function which returned the current count, to show it cleaner.
Yes, @Seabizkit I agree we can write a different function to return a number of rows in the current table.
0

This code might solve your problem.

var btn = document.getElementById('btn');
btn.onclick = myFunction;

function myFunction() {
    validateForm()
    addRow()
}
 var rowNumber = 0;

function addRow() {
 
    //Get data from filled in form
    var form = document.getElementById('form');
    var newData = [];
    for(var i = 0; i < form.length; i++) {
       newData[i] = form.elements[i].value;
    }

    if(validateForm() == true) {
    rowNumber++;
        //Put data in table
      
        var table = document.getElementById('table');
        var newRow = table.insertRow();
      
        newRow.innerHTML = `<tr><td>${rowNumber}</td></tr>`;
      
        for(var i = 0; i < 3; i++) {
          newRow.innerHTML += `<tr><td>${newData[i]}</td></tr>`;
        }
    }
    form.reset();
}


function validateForm() {
    var f = document.getElementById('form');

    if(f.fname.value == '') {
        alert('Please fill in first name');
        return false;
    }
    if(f.lname.value == '') {
        alert('Please fill in last name');
        return false;
    }
    if(f.points.value == '') {
        alert('Please fill in points');
        return false;
    }
    if(isNaN(f.points.value)) {
        alert('Points should be a number')
        return false
    }

    return true;

}
input[type="text"] {
  padding:10px;
  font-size:16px;
}
#btn {
  padding:15px 25px;
  border: 0;
  background: #f90;
  color: #fff;
  border-radius: 3px;
  font-size:16px;
  cursor: pointer;
  margin: 20px auto;
}
#table tr td {
  font-size: 16px;
  padding: 10px 20px;
  border: 2px solid #000;
  font-family: sans-serif;
}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <form action="" id="form">
    <input type="text" name="fname" placeholder="Fname">
    <input type="text" name="lname" placeholder="Lname">
    <input type="text" name="points" placeholder="Points">
  </form>
  <button id="btn">Add Row</button>
  <table id="table"></table>
</body>
</html>

1 Comment

Your solution has a bug in it, you're incrementing row number before validating the form. So if validation fails the first time and I enter valid values and try again then row number will be updated as 2.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.