Dynamic table with up and down button and add & delete buttons

Discussion in 'JavaScript' started by celia05es, Dec 10, 2007.

  1. #1
    Hi,
    I am using jsp. At one point, I have, let's say, in a list, around 200 items.
    I need to list them. I would like to list them every 20 items (up and down buttons)... but the user can as well add an item and delete it.
    I would like to do it without having to refresh the page each time.... for this reason I thing dynamic table is the best but could you help me with the script?
    I have bits of the script like removing a cell or adding a cell... but I don't know how to do it globally?
    I suppose the 200 items will have to be loaded first in a javascript array so it can be accessed by JS.
    I need to draw a table such a :

    <column title>
    n1 <DELETE>
    n2 <DELETE>
    .....
    n20 <DELETE>
    <ADD>
    <PREVIOUS> <NEXT>
    Could you help please?

    THanks
     
    celia05es, Dec 10, 2007 IP
  2. hrcerqueira

    hrcerqueira Peon

    Messages:
    125
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #2
    There are some different ways of doing that. Some of them are easier than the other. If you just really want to load all the 200 items it's easier, but you can use ajax to load them when they're needed, and that's a bit trickier.

    But either way, that's quite a large and laborious script. You'ld be better googling for a pre-made one, or if you want to do it yourself, just ask and I'll try to point you in the right direction, and give some help with the coding.
     
    hrcerqueira, Dec 10, 2007 IP
  3. celia05es

    celia05es Guest

    Messages:
    21
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    THanks for your answer. Here is what I've done so far.
    I have 2 problems:
    - The table contents can be found in a database. Each time the user adds (not done for the moment) or deletes an item, the database has to be updated. I was thinking of getting the items once at the beginning and then save the values in a hidden field "items". Then, each time an item was added or deleted, I would update this field... and would update the database. Certainly it is not the best way of doing it but I cant think of another one.
    - The table is shown using the "paintTable()" function (loaded with OnLoad)
    Since the table is quite big, I want to show it every x entries (for the moment I have chosen MAXLENGTH=5). The user can then press "Previous" or "next" buttons. The problem happens when I want to delete an item.... I don't delete the good one!!
    For instance, suppose I have 7 items
    The first table I paint has:
    1. item1
    2. item2
    3. item3
    4. item4
    5. item5

    Then the 2nd table (with the next button)
    6. item6
    7. item7
    Now, if I want to delete item number 6, since the index is one... it is item1 that is deleted and no item6 !!! How can I solve the problem!!!

    Could you help me with it?
    Many, many thanks!

    
    <html>
    <head>
    <title>Insert/Delete Table Row using DOM</title>
    <link rel="stylesheet" type="text/css" href="style.css">
    <style type="text/ccs">
    <!--
    
    form {border:1px solid blue;}
    div {border:1px solid red; width:150px; overflow:auto;}
    .selectBox { font-size:xx-small;overflow:auto;}
    
    #tblSample td,th {padding:0.5em;}
    .classy0 { background-color: #234567; color:#89abcd;}
    .classy1 {background-color: #89abcd; color:@234567;}
    -->
    </style>
    <%@ include file="javascriptLib.html" %>
    <script language="JavaScript" type="text/JavaScript">
    
    <!--- oculta el script para navegadores antiguos
    var START_INDEX=0;
    var INPUT_NAME_PREFIX = 'inputName'; // this is being set via script
    var TABLE_NAME = 'vnp_list'; // this should be named in the HTML
    var LABEL_NAME = 'label_list';
    var ROW_BASE = 1; // first number (for display)
    var MAXLENGTH=5;
    
    
    Array.prototype.remove = function(from, to) {
      var rest = this.slice((to || from) + 1 || this.length);
      this.length = from < 0 ? this.length + from : from;
      return this.push.apply(this, rest);
    };
    
    function myRowObject(one,two)
    {
    this.one = one; // text object
    this.two = two; // input text object
    }
    
    function deleteCurrentRow(obj)
    {
    var delRow = obj.parentNode.parentNode;
    var tbl = delRow.parentNode.parentNode;
    var rIndex = delRow.sectionRowIndex;
    var rowArray = new Array(delRow);
    deleteRows(rowArray);
    reorderRows(tbl, rIndex);
    
    // Delete row from vlrNumberPrefix field
    var vnp=document.forms[0].vnp.value;
    
    var sarray=vnp.split("|");
    sarray.remove(rIndex);
    alert("despues sarray="+sarray+" "+sarray.length);
    var str="";
    for (i=0;i<sarray.length-1;i++)
    {
      str=str+sarray[i]+"|";
    }
    str=str+sarray[sarray.length-1];
    document.forms[0].vnp.value=str;
    if (START_INDEX == sarray.length)
        START_INDEX = START_INDEX - MAXLENGTH;
    if (START_INDEX < 0)
        START_INDEX = 0;
    paintTable(START_INDEX);
    }
    
    function deleteRows(rowObjArray)
    {
    for (var i=0; i<rowObjArray.length; i++)
    {
      var rIndex = rowObjArray[i].sectionRowIndex;
      rowObjArray[i].parentNode.deleteRow(rIndex);
    }
    }
    
    function reorderRows(tbl, startingIndex)
    {
    if (tbl.tBodies[0].rows[startingIndex])
    {
      var count = startingIndex + ROW_BASE;
      for (var i=startingIndex; i<tbl.tBodies[0].rows.length; i++)
      {
        // CONFIG: next line is affected by myRowObject settings
        tbl.tBodies[0].rows[i].myRow.one.data = count; // text
    
        // CONFIG: next line is affected by myRowObject settings
        tbl.tBodies[0].rows[i].myRow.two.name = INPUT_NAME_PREFIX + count;
        var tempVal = tbl.tBodies[0].rows[i].myRow.two.value.split(' ');
        tbl.tBodies[0].rows[i].className = 'classy' + (count % 2);
    
        count++;
      }
    }
    }
    
    function clearTable(option)
    {
    var tbl = document.getElementById(TABLE_NAME);
    if (option != 0)
      tbl=  document.getElementById(LABEL_NAME);
    //var lastRow = tbl.tBodies[0].rows.length;
    var lastRow = tbl.rows.length;
    var i=lastRow-1;
    while (i>=0)
    {
     tbl.deleteRow(i);
     i--;
    }
    }
    
    function addRowToTable(val)
    {
      var tbl = document.getElementById(TABLE_NAME);
      var nextRow = tbl.tBodies[0].rows.length;
      var iteration = nextRow + ROW_BASE;
      // add the row
      var row = tbl.tBodies[0].insertRow(nextRow);
    
      // CONFIG: requires classes named classy0 and classy1
      row.className = 'classy' + (iteration % 2);
    
      // CONFIG: This whole section can be configured
    
      // cell 0 - index
      var cell0 = row.insertCell(0);
      var textNode = document.createTextNode(iteration);
      cell0.appendChild(textNode);
    
      // cell 1 - input text
      var cell1 = row.insertCell(1);
      var txtInp = document.createElement('input');
      txtInp.setAttribute('type', 'text');
      txtInp.setAttribute('name', INPUT_NAME_PREFIX + iteration);
      txtInp.setAttribute('size', '62');
      txtInp.setAttribute('value', val); // iteration included for debug purposes
      txtInp.readOnly = true;
      cell1.appendChild(txtInp);
    
      // cell 2 - delete button
      //-----------------------
      var cell2 = row.insertCell(2);
      var btnEl = document.createElement('input');
      btnEl.setAttribute('type', 'button');
      btnEl.setAttribute('value', 'Delete');
      btnEl.onclick = function () {deleteCurrentRow(this)};
      cell2.appendChild(btnEl);
    
      // Store the myRow object in each row
      row.myRow = new myRowObject(textNode,txtInp);
    
    }
    
    function paintTable(index)
    {
    START_INDEX=index;
    
    var maxLine=index+MAXLENGTH;
    clearTable(0);
    
    // add Row with delete and insert options
    //----------------------------------------
    services=document.forms[0].vnp.value;
    if ((services != null) && (services != ""))
    {
      var services_array=services.split("|");
      sLength=services_array.length ;
    
      if (services_array.length < maxLine)
           maxLine=sLength;
    
      // add Row with delete options
      //-----------------------------
       for (var i=index; i < maxLine; i++)
       {
         val=services_array[i];
          addRowToTable(val);
       }
    
       showLabel(index,sLength);
      }
    }
    
    function showLabel(index,max)
    {
    clearTable(1);
    
    next_val=index+MAXLENGTH;
    prev_val=index-MAXLENGTH;
    var tbl = document.getElementById(LABEL_NAME);
    var nextRow = tbl.tBodies[0].rows.length;
    
    // add Previous and/or Next buttons
    //---------------------------------
    var row = tbl.tBodies[0].insertRow(nextRow);
    var celNo=0;
    if (index !=0)
    {
      var cell0 = row.insertCell(celNo);
      var btnEl0 = document.createElement('input');
      btnEl0.setAttribute('type', 'button');
      btnEl0.setAttribute('value', 'Previous');
      btnEl0.onclick = function () {paintTable(prev_val)};
      cell0.appendChild(btnEl0);
      celNo++;
    }
    if (next_val < max)
    {
      var cell1 = row.insertCell(celNo);
      var btnEl1 = document.createElement('input');
      btnEl1.setAttribute('type', 'button');
      btnEl1.setAttribute('value', 'Next');
      btnEl1.onclick = function () {paintTable(next_val)};
      cell1.appendChild(btnEl1);
    }
    }
    
    // end hiding from old browsers -->
    </script>
    </script>
    </head>
    <body onLoad=paintTable(0)>
    <P><center><B>Vlr Address List</B></center>
    <P>
    <%
    // Get Address List
    //----------------
    String addressList="";
    addressList="1|2|3|4|5|6|7|8|9|10|11";
    %>
    <form onSubmit="return false" method="post" name="my_form" action="">
    <table border= "2" cellspacing="0" id="vnp_list" >
    <tbody></tbody>
    <input type=hidden name="vnp" value='<%=addressList%>'>
    </table>
    <P><P><table border="1" id="label_list">
    <tbody></tbody>
    </form>
    </body>
    </html>
    
    
    Code (markup):
     
    celia05es, Dec 11, 2007 IP
  4. celia05es

    celia05es Guest

    Messages:
    21
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Actually, the problem caomes with the paintTable. When I delete an item, the "reorderRows" is called.... but then only 4 items are shown and I need 5 items to be shown... that is to say that if there are more items to be shown, the next item has to be shown in this page. How can I do it?
     
    celia05es, Dec 11, 2007 IP
  5. celia05es

    celia05es Guest

    Messages:
    21
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #5
    Actually, I think I have solved the 2nd problem I had.... now, could you tell me if the update can be done differently?
    Many thanks
    Elisabeth
    
    <html>
    <head>
    <title>Insert/Delete Table Row using DOM</title>
    <link rel="stylesheet" type="text/css" href="style.css">
    <style type="text/ccs">
    <!--
    
    form {border:1px solid blue;}
    div {border:1px solid red; width:150px; overflow:auto;}
    .selectBox { font-size:xx-small;overflow:auto;}
    
    #tblSample td,th {padding:0.5em;}
    .classy0 { background-color: #234567; color:#89abcd;}
    .classy1 {background-color: #89abcd; color:@234567;}
    -->
    </style>
    <%@ include file="javascriptLib.html" %>
    <script language="JavaScript" type="text/JavaScript">
    <!--- oculta el script para navegadores antiguos
    var START_INDEX=0;
    var INDEX=0;
    var INPUT_NAME_PREFIX = 'inputName'; // this is being set via script
    var TABLE_NAME = 'vnp_list'; // this should be named in the HTML
    var LABEL_NAME = 'label_list';
    var ROW_BASE = 1; // first number (for display)
    var MAXLENGTH=5;
    
    
    Array.prototype.remove = function(from, to) {
      var rest = this.slice((to || from) + 1 || this.length);
      this.length = from < 0 ? this.length + from : from;
      return this.push.apply(this, rest);
    };
    
    function myRowObject(one)
    {
    this.one = one; // input text object
    }
    
    function deleteCurrentRow(obj)
    {
    var delRow = obj.parentNode.parentNode;
    var tbl = delRow.parentNode.parentNode;
    var rIndex = delRow.sectionRowIndex;
    var rowArray = new Array(delRow);
    deleteRows(rowArray);
    x=INDEX+rIndex;
    // Delete row  x from vlrNumberPrefix field
    var vnp=document.forms[0].vnp.value;
    var sarray=vnp.split("|");
    sarray.remove(x);
    var str="";
    for (i=0;i<sarray.length-1;i++)
    {
      str=str+sarray[i]+"|";
    }
    str=str+sarray[sarray.length-1];
    document.forms[0].vnp.value=str;
    if (START_INDEX == sarray.length)
        START_INDEX = START_INDEX - MAXLENGTH;
    if (START_INDEX < 0)
        START_INDEX = 0;
    paintTable(2,START_INDEX);
    }
    
    function deleteRows(rowObjArray)
    {
    var rIndex = rowObjArray[0].sectionRowIndex;
    rowObjArray[0].parentNode.deleteRow(rIndex);
    }
    
    function clearTable(option)
    {
    var tbl = document.getElementById(TABLE_NAME);
    if (option != 0)
      tbl=  document.getElementById(LABEL_NAME);
    //var lastRow = tbl.tBodies[0].rows.length;
    var lastRow = tbl.rows.length;
    var i=lastRow-1;
    while (i>=0)
    {
     tbl.deleteRow(i);
     i--;
    }
    }
    
    function addRowToTable(val)
    {
      var tbl = document.getElementById(TABLE_NAME);
      var nextRow = tbl.tBodies[0].rows.length;
      var iteration = nextRow + ROW_BASE;
      // add the row
      var row = tbl.tBodies[0].insertRow(nextRow);
    
      // CONFIG: requires classes named classy0 and classy1
      row.className = 'classy' + (iteration % 2);
    
      // CONFIG: This whole section can be configured
    
      // cell 0 - input text
      var cell0 = row.insertCell(0);
      var txtInp = document.createElement('input');
      txtInp.setAttribute('type', 'text');
      txtInp.setAttribute('name', INPUT_NAME_PREFIX + iteration);
      txtInp.setAttribute('size', '62');
      txtInp.setAttribute('value', val); // iteration included for debug purposes
      txtInp.readOnly = true;
      cell0.appendChild(txtInp);
    
      // cell 1 - delete button
      //-----------------------
      var cell1 = row.insertCell(1);
      var btnEl = document.createElement('input');
      btnEl.setAttribute('type', 'button');
      btnEl.setAttribute('value', 'Delete');
      btnEl.onclick = function () {deleteCurrentRow(this)};
      cell1.appendChild(btnEl);
    
      // Store the myRow object in each row
      row.myRow = new myRowObject(txtInp);
    
    }
    
    function paintTable(option,index)
    {
    if (option == 0) INDEX=INDEX-MAXLENGTH;
    if (option == 1) INDEX=INDEX+MAXLENGTH;
    START_INDEX=index;
    
    var maxLine=index+MAXLENGTH;
    clearTable(0);
    
    // add Row with delete and insert options
    //----------------------------------------
    services=document.forms[0].vnp.value;
    if ((services != null) && (services != ""))
    {
      var services_array=services.split("|");
      sLength=services_array.length ;
    
      if (services_array.length < maxLine)
           maxLine=sLength;
    
      // add Row with delete options
      //-----------------------------
       for (var i=index; i < maxLine; i++)
       {
         val=services_array[i];
          addRowToTable(val);
       }
    
       showLabel(index,sLength);
      }
    }
    
    function showLabel(index,max)
    {
    clearTable(1);
    
    next_val=index+MAXLENGTH;
    prev_val=index-MAXLENGTH;
    var tbl = document.getElementById(LABEL_NAME);
    var nextRow = tbl.tBodies[0].rows.length;
    
    // add Previous and/or Next buttons
    //---------------------------------
    var row = tbl.tBodies[0].insertRow(nextRow);
    var celNo=0;
    if (index !=0)
    {
      var cell0 = row.insertCell(celNo);
      var btnEl0 = document.createElement('input');
      btnEl0.setAttribute('type', 'button');
      btnEl0.setAttribute('value', 'Previous');
      btnEl0.onclick = function () {paintTable(0,prev_val)};
      cell0.appendChild(btnEl0);
      celNo++;
    }
    
    if (next_val < max)
    {
      var cell1 = row.insertCell(celNo);
      var btnEl1 = document.createElement('input');
      btnEl1.setAttribute('type', 'button');
      btnEl1.setAttribute('value', 'Next');
      btnEl1.onclick = function () {paintTable(1, next_val)};
      cell1.appendChild(btnEl1);
    }
    }
    
    // end hiding from old browsers -->
    </script>
    </script>
    </head>
    <body onLoad=paintTable(2,0)>
    <P><center><B>Vlr Address List</B></center>
    <P>
    <%
    // Get Address List
    //----------------
    String addressList="";
    addressList="1|2|3|4|5|6|7|8|9|10|11";
    %>
    <form onSubmit="return false" method="post" name="my_form" action="">
    <table border= "2" cellspacing="0" id="vnp_list" >
    <tbody></tbody>
    <input type=hidden name="vnp" value='<%=addressList%>'>
    </table>
    <P><P><table border="1" id="label_list">
    <tbody></tbody>
    </form>
    </body>
    </html>
    
    Code (markup):
     
    celia05es, Dec 11, 2007 IP
  6. hrcerqueira

    hrcerqueira Peon

    Messages:
    125
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #6
    Sorry for taking so long to reply.

    I see you're no a complete amateur in javascript, so, let me give you some gidelines. This is your starting table for example:

    
    <table id="atable">
       <thead>
       <tr>
          <td>column 1</td>
          <td>column 2</td>
       </tr>
       </thead>
    </table>
    
    Code (markup):
    first, create a array to store the rows as objects:

    
    var rows = [];
    
    Code (markup):
    now, in order to append a row, you can do something like this:

    
    function createRow(value1, value2) {
    
    var newrow = document.createElement('TR');
    var newtd1 = document.createElement('TD');
    var newtd2 = document.createElement('TD');
    
    newtd1.innerHTML = value1;
    newtd2.innerHTML = value2;
    
    newrow.appendChild(newtd1);
    newrow.appendChild(newtd2);
    
    document.getElementById('atable').appendChild('newrow');
    
    return newrow;
    
    }
    
    Code (markup):
    to save a new row to the database, create a jsp document dedicated to that, saverow.jsp for example:

    
    <%
        String value1 = request.getParameter("value1");
        String value2 = request.getParameter("value2");
    
        //save value1 and value2 to the database using your favourite method, stored procedures, torque, hibernate, anything....
    
        //retrieve the new row primary key as the output
    %>
    
    Code (markup):
    and to store it from the browser, using ajax, you can use SACK for example, just google for it, download the file and include it on your page, then create a function:

    
    function saveRowToDb(value1, value2) {
       var s = new sack('saverow.jsp');
       s.encVar('value1', value1);
       s.encVar('value2', value2);
    
       s.onComplete = function() {
          newrowpkey = s.response;
          newrow = createRow(value1, value2);
    
          rows.push({row: newrow, pkey: newrowpkey});
       }
    }
    
    Code (markup):
    Give it a try to this step first, the I'll help you with the rest, if you like this method.
     
    hrcerqueira, Dec 12, 2007 IP
    hogan_h likes this.
  7. celia05es

    celia05es Guest

    Messages:
    21
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #7
    Thank you so much! I think that this will help me a lot for what I want to do. I think I can manage with the rest.
    Once again, thank you!
     
    celia05es, Dec 14, 2007 IP