wdfeww wdfeww - 1 month ago 11
HTML Question

How to delete row in table?

I want delete row which I created in function

add()
. When I use function
deleteRow()
row will be deleted but I can't use my
add()
function again. Someone knows why?

var trIdP =0;
function add() {
var typeP = document.getElementById("typeP").value;
var valueP = document.getElementById("valueP").value;
var newText = document.createTextNode(typeP);
var newText2 = document.createTextNode(valueP+" Eur");
var newText3 = document.createTextNode("button");
var tablePr = document.getElementById("tableP").getElementsByTagName('tbody')[0];
if ((typeP != "") && (valueP != "")) {
var newRow = tablePr.insertRow(trIdP);
newRow.id = ("trP"+trIdP);
var newCell1 = newRow.insertCell(0);
var newCell2 = newRow.insertCell(1);
var newCell3 = newRow.insertCell(2);

newCell1.appendChild(newText);
newCell2.appendChild(newText2);
newCell3.innerHTML = "<a onclick=\"deleteRow("+trIdP+")\"><img src=\"x.gif\" alt=\"Delete row\"></a>";

document.getElementById("typeP").value = "";
document.getElementById("valueP").value = "";

trIdP++;
}
}

function deleteRow(id){
document.getElementById("trP"+id).remove();
}

Answer

You're forgetting to decrease the trIdP counter.

// Code goes here

var trIdP = 0;

function add() {
  var typeP = document.getElementById("typeP").value;
  var valueP = document.getElementById("valueP").value;
  var newText = document.createTextNode(typeP);
  var newText2 = document.createTextNode(valueP + " Eur");
  var newText3 = document.createTextNode("button");
  var tablePr = document.getElementById("tableP").getElementsByTagName('tbody')[0];
  if ((typeP !== "") && (valueP !== "")) {
    var newRow = tablePr.insertRow(trIdP);
    newRow.id = "trP" + trIdP;
    var newCell1 = newRow.insertCell(0);
    var newCell2 = newRow.insertCell(1);
    var newCell3 = newRow.insertCell(2);

    newCell1.appendChild(newText);
    newCell2.appendChild(newText2);
    newCell3.innerHTML = "<a onclick=\"deleteRow(" + trIdP + ")\"><div>X</div></a>";

    document.getElementById("typeP").value = "";
    document.getElementById("valueP").value = "";

    trIdP++;
  }
}

function deleteRow(id) {
  document.getElementById("trP" + id).remove();
  trIdP--;
}

Check out this plunker