Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Strange row number behaviour with javascript generated table 1

Status
Not open for further replies.

deeciple

Technical User
Mar 1, 2012
70
US
Hi All,

I have a script that runs on my page load and pulls some data from a database to build a table with.

JavaScript:
function makeTable(tableID){

  var str = "<?php echo $row_rstRequestDetails['tblEquipRequestID']; ?>";
  var body = document.getElementsByTagName("fieldset")[0];
  var tbl = document.createElement("table");
  var tblBody = document.createElement("tbody");
  
  tbl.appendChild(tblBody);
  body.appendChild(tbl);

  tbl.setAttribute("id", "dataTable");
  tbl.setAttribute("width", "100%");
  tbl.setAttribute("border", "0");

  xmlhttp=new XMLHttpRequest();
  xmlhttp.onreadystatechange=function() {

    if (xmlhttp.readyState==4 && xmlhttp.status==200) {
      if (xmlhttp.responseText) {

        var itemsList = JSON.parse(xmlhttp.responseText);

        for(var i = 0; i < itemsList.length; i++) {
          var table = document.getElementById(tableID);               
          var rowCount = table.rows.length;             
          var row = table.insertRow(rowCount);
          
          var cell0 = row.insertCell(0);
          cell0.setAttribute("width","33%");
          var element0 = document.createElement("input");
          element0.type = "text";
          element0.setAttribute("name","Equip[]");
          element0.setAttribute("readonly","true");
          element0.setAttribute("class","search");
          element0.value = itemsList[i].EquipNeeded;             
          cell0.appendChild(element0);

          var cell1 = row.insertCell(1);
          cell1.setAttribute("width","33%");
          var element1 = document.createElement("input");
          element1.type = "text";
          element1.setAttribute("name","Qty[]");
          element1.setAttribute("readonly","true");
          element1.setAttribute("class","search");  
          element1.value = itemsList[i].Quantity;             
          cell1.appendChild(element1);
          
          var cell2 = row.insertCell(2);
          cell2.setAttribute("width","33%");
          var element2 = document.createElement("input");
          element2.type = "button";
          element2.setAttribute("name","remove");
          element2.setAttribute("class","button");
          // alert("rowCount is "+rowCount);
          element2.onclick = function(){deleteRow(tableID,rowCount);}
          element2.value = "Remove";             
          cell2.appendChild(element2);
        }        
      }
    }
  }

xmlhttp.open("GET","query-requested-equip.php?tblEquipRequestID="+str,true);
xmlhttp.send();
}

Now I also have a similar script that is called via a onclick event so the user can manually add more rows to this table and another for the deletion of rows from the table:

JavaScript:
function addRow(tableID) {
var oHidden = frmEquipmentRequest.elements["EquipNeeded"];
var oDDL = frmEquipmentRequest.elements["EquipNeeded_ddl"];
var oTextbox = frmEquipmentRequest.elements["EquipNeeded_txt"];
var Quantity = document.getElementById('Quantity');
var n = ~~Number(Quantity.value);

if (oHidden && oDDL && oTextbox)
    oHidden.value = (oDDL.value == "") ? oTextbox.value : oDDL.value;

var varDetails = [oHidden, Quantity];
var arrayLength = varDetails.length;

  for(var i=0; i<arrayLength; i++) {                 
    if (varDetails[i].value=="") {
      alert("Please complete all fields before adding.");
      return;
    }
  } 

  if (n != Quantity.value || n <= 0 || isNaN(Quantity.value)){
    alert("Quantity must be an integer.");
    Quantity.value="";
    return;
  }

    if (!document.getElementById(tableID)) {

      var body = document.getElementsByTagName("fieldset")[0];
      var tbl = document.createElement("table");
      var tblBody = document.createElement("tbody");
      
      tbl.appendChild(tblBody);
      body.appendChild(tbl);

      tbl.setAttribute("id", "dataTable");
      tbl.setAttribute("width", "100%");
      tbl.setAttribute("border", "0");
    }
    
  var table = document.getElementById(tableID);               
  
  var rowCount = table.rows.length;             
  var row = table.insertRow(rowCount);
  
  var cell0 = row.insertCell(0);
  cell0.setAttribute("width","33%");
  var element0 = document.createElement("input");
  element0.type = "text";
  element0.setAttribute("name","Equip[]");
  element0.setAttribute("readonly","true");
  element0.setAttribute("class","search");
  element0.value = oHidden.value;             
  cell0.appendChild(element0);
  oDDL.value="";
  oTextbox.value="";
  oTextbox.style.display="none";              
  
  var cell1 = row.insertCell(1);
  cell1.setAttribute("width","33%");
  var element1 = document.createElement("input");
  element1.type = "text";
  element1.setAttribute("name","Qty[]");
  element1.setAttribute("readonly","true");
  element1.setAttribute("class","search");  
  element1.value = Quantity.value;             
  cell1.appendChild(element1);
  Quantity.value=""; 
  
  var cell2 = row.insertCell(2);
  cell2.setAttribute("width","33%");
  var element2 = document.createElement("input");
  element2.type = "button";
  element2.setAttribute("name","remove");
  element2.setAttribute("class","button");
  element2.onclick = function(){deleteRow(tableID,rowCount);}
  element2.value = "Remove";             
  cell2.appendChild(element2);
  }

function deleteRow(tableID,tr) {
	// alert('tableID is '+tableID+' and rowCount is '+tr);
	if (document.getElementById(tableID)) {
    try {             
	  var table = document.getElementById(tableID);               
	  var rowCount = table.rows.length;                 
        for(var i=0; i<rowCount; i++) {                 
            var row = table.rows[i];  
			//alert ("row is "+i);               
            if(i == tr) {                     
                table.deleteRow(i);                     
                i++; 
                if(rowCount==0){
                  table.parentNode.removeChild(table); 
                }
            }               
        }             
    }catch(e) {                 
        alert(e);             
    }         
  }
}

I can remove rows that were added manually to the table but for some reason I cannot remove rows that were added by the makeTable() script on page load. It appears that the makeTable() script is attaching the last row number to the onclick event which is passed to my deleteRow() script, no matter which row I click to delete. This is odd since I tested by adding an alert to see the value of the rowCount variable that I am attaching to my onclick event in the makeTable() script and it seems to be the correct value for each iteration of my loop.

What am I missing here?

Thanks in advance for any help.

Ken
 
rather than passing rowcount why not just have the onclick event call a function and in that function you traverse the dom up from the clicked button to the nearest tr and then remove that?

much cleaner I suspect?
 
Hi jpadie,

I tried this:

JavaScript:
{
    var node = this;
    while ( node.tagName != "TR" )
    {
        node = node.parentNode;
        if ( node == null ) return; // ??? something went wrong
    }
    node.parentNode.removeChild( node );
}

...but it doesn't seem to be doing anything :(

Is this what you meant?

Thanks,

Ken
 
Never mind. It was simpler than I thought:

JavaScript:
function deleteRow(r) {
    var i = r.parentNode.parentNode.rowIndex;
    document.getElementById("dataTable").deleteRow(i);
}
 
On the first code snip of the two if I were not using event listeners I would pass this as an argument.
Code:
onclick="deleterow(this)"

then in the function
Code:
Function deleterow(n){
 var curSearch = "TR"
  while (n.parentnode){
   if (n.nodeType == 1 && n.nodeName == curSearch){
    if(curSearch == "TR") {
     var i = n.rowIndex;
     curSearch = "TABLE";
    } else {
     n.deleterow(i);
    }
   }
   n = n.parentNode;
 }
}

Nb not tested and typed directly into mobile browser....

This is all much more straight forward using jQuery.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top