INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Jobs

Strange row number behaviour with javascript generated table

Strange row number behaviour with javascript generated table

Strange row number behaviour with javascript generated table

(OP)
Hi All,

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

CODE --> 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:

CODE --> 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

RE: Strange row number behaviour with javascript generated table

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?

RE: Strange row number behaviour with javascript generated table

(OP)
Hi jpadie,

I tried this:

CODE --> 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

RE: Strange row number behaviour with javascript generated table

(OP)
Never mind. It was simpler than I thought:

CODE --> Javascript

function deleteRow(r) {
    var i = r.parentNode.parentNode.rowIndex;
    document.getElementById("dataTable").deleteRow(i);
} 

RE: Strange row number behaviour with javascript generated table

Well done.

RE: Strange row number behaviour with javascript generated table

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.

Red Flag This Post

Please let us know here why this post is inappropriate. Reasons such as off-topic, duplicates, flames, illegal, vulgar, or students posting their homework.

Red Flag Submitted

Thank you for helping keep Tek-Tips Forums free from inappropriate posts.
The Tek-Tips staff will check this out and take appropriate action.

Reply To This Thread

Posting in the Tek-Tips forums is a member-only feature.

Click Here to join Tek-Tips and talk with other members!

Resources

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close