Search code examples
javascriptcell

Giving unique id to table cell


I have created a table.

I have text input where I type some text. It refers to some element with special values.

When I click a button the productname is added to the table (using insertCell()).

I want to give a unique id to every new table element.

function add1() {
  var row, cell;
  var productname = document.getElementById("produkt1").value; // text input
  var table = document.getElementById("pos1"); // button near text input

  if(productname === "Egg") {
    p = ["Egg", "", 20, 10, 11, 101];
  }
  if(productname === "Milk") {
    p = ["Milk", "", 30, 5, 12, 75];
  }

  row = table.insertRow(2);
  var c_id = 0;

  for (var i = 0; i < p.length ; i++) {
    cell = row.insertCell(i);
    cell.innerHTML = p[i];

    for (var j = 0; j < 1 ; j++) {
      cell.id = 'tdp1' + k_id;
      c_id++; 
    }
  } // It only works for one element, and the others have the same id as elements from row1
}

Solution

  • I found solution:

    function add1() {
    var row, cell;
    var productname = document.getElementById("produkt1").value;
    var table = document.getElementById("pos1");
    if(productname === "Egg") {
    p = ["Egg", "", 20, 10, 11, 101];
    }
    if(productname === "Milk") {
    p = ["Milk", "", 30, 5, 12, 75];
    }
    var cells = document.getElementsByClassName("pos");
    row = table.insertRow(2);
    for(var i = 0; i < p.length ; i++){
    cell = row.insertCell(i);
    cell.innerHTML = p[i];
    cell.className = "pos";
    for(var j = 0; j < cells.length ; j++){
    cell.id = 'tdp1' + j;
    }
    }
    

    I gave created cell a className. It's working, but thank you for help. :)