views:

371

answers:

2

Group, I have a table that is dynamically built with device ids. I have a "swapCell" that moves the cells up and down when the user clicks on (up/dwn) buttons. I have a delete row function that deletes current row.

-Problem is: If I have six rows (1,2,3,4,5,6) and six id's (id=row1,id=row2,id=row3,id=row4,id=row5,id=row6)

-And delete "row 2 and row 4" I have new rows (1,2,3,4) and new (id=row1,id=row3,id=row5,id=row6)

-But I would like to have "id's" the same as row number after I delete that current row.


function swapcells(idA,idB){
    var cellA=document.getElementById('cell'+idA); 
    var cellB=document.getElementById('cell'+idB); 
    if(cellA&&cellB){ 
        var temp=cellA.innerHTML; 
        cellA.innerHTML=cellB.innerHTML; 
        cellB.innerHTML=temp; 
    }
}  
function deleteRows(rowObjArray){
    if (hasLoaded) {
        for (var i=0; i<rowObjArray.length; i++) {
            var rIndex = rowObjArray[i].sectionRowIndex;
            rowObjArray[i].parentNode.deleteRow(rIndex);
        }
    }
}
+2  A: 

ID's based on Index with pure Javascript

function reIDRows() {
  var rows = document.getElementById("myTable").getElementsByTagName("tr");
  for (var i = 0; i < rows.length; i++) {
    rows[i].id = i;
  }
}

ID's based on Index with jQuery

function reIDRows() {
  $("tr").each(function(i,o){
    $(this).attr("id", i);
  });
}
Jonathan Sampson
glad you fixed that.
Jonathan Fingland
@Jonathan Unfortunately I assume that people are using jQuery too often :)
Jonathan Sampson
I have to admit that jquery or prototype (or the like) would be preferable to vanilla JS for most things and particularly so for Chad's case. Still I tend to feel it's important to know _how_ to do vanilla JS before relying on the frameworks too much.
Jonathan Fingland
@Jonathan I agree completely. Without (at the very least) a moderate understanding of Javascript, nobody should use jQuery.
Jonathan Sampson
My table row id is based on iterations----if (hasLoaded) { var tbl = document.getElementById(TABLE_NAME); var nextRow = tbl.tBodies[0].rows.length; var iteration = nextRow + ROW_BASE; if (num == null) { num = nextRow; } else { iteration = num + ROW_BASE; }
Chad Sellers
@ChadSellers: I cannot address problems that weren't included in your question. The solutions I provided solve the problem you presented. If you have additional details, update your question.
Jonathan Sampson
A: 

Try to loop over the datatable and count the number of rows. Set each id field to the counted rownumber in the loop.

Ropstah
You should do this every time a row has been deleted.
Ropstah
I have a iteration function that does this and adds the row number for me.--------ROW_BASE=1;var iteration = nextRow + ROW_BASE;if (num == null) {num = nextRow;} else {iteration = num + ROW_BASE;}
Chad Sellers