« powrót

Manipulacje na tabeli [JavaScript]

Opublikowano: 2010-12-25 , wyświetlono: 8839

W przykładzie pokazana jest modyfikacja tabeli z użyciem pól formularza w komórkach

Tabela z formularzem
tekst element input element combo


<html>

<body>
<style>
.rowItem { font-size: 12px; background-color: #eee; }
</style>

<script type="text/javascript">

function addRowToTable()
{
  var table = document.getElementById("table");
  var lastRow = table.rows.length;
  var row = table.insertRow(lastRow);
  var i = lastRow;
  
  // cell 1 - static text
  var cell = row.insertCell(0);
  cell.setAttribute("class", "rowItem");
  var textNode = document.createTextNode(i);
  cell.appendChild(textNode);
  
  // cell 2 - inout text
  cell = row.insertCell(1);
  cell.setAttribute("class", "rowItem");
  var el = document.createElement("input");
  el.type = "text";
  el.name = "field" + i;
  el.size = "40";
  el.setAttribute("class", "Text");
  cell.appendChild(el);
  
  // cell 3 - combo
  cell = row.insertCell(2);
  cell.setAttribute("class", "rowItem");
  el = document.createElement("select");
  el.name = "type" + i;
  el.options[0] = new Option("element1", "element1");
  el.options[1] = new Option("element2", "element2");
  el.options[2] = new Option("element3", "element3");
  el.setAttribute("class", "Text");
  cell.appendChild(el);

}

function deleteAllRows()
{
  var table = document.getElementById("table");
  
  while (table.hasChildNodes())
    table.removeChild(table.firstChild)
}

function deleteRows()
{
  var table = document.getElementById("table");
 
  while (table.rows.length > 1)
    table.deleteRow(table.rows.length - 1);
}

function deleteTable()
{
  var tableDiv = document.getElementById("tableDiv");
  var table = document.getElementById("table");
  tableDiv.removeChild(table);
}

</script>

<form name="formTable" action="#">

<fieldset>
  <legend>Tabela z formularzem</legend>

  <div id="tableDiv">
    <table id="table" border="0" cellspacing="1" cellpadding="2" bgcolor="#fff" width="100%">
    
    <tr>
    <td class="rowItem">tekst</td>
    <td class="rowItem">element input</td>
    <td class="rowItem">element combo</td>
    </tr>
    
    </table>
  </div>

</fieldset>

<input type="button" name="addRow" value="Dodaj wiersz" onclick="addRowToTable();">
<input type="button" name="delAll" value="Usuń wszystkie wiersze" onclick="deleteAllRows();">
<input type="button" name="delRows" value="Usuń wiersze bez naglowka" onclick="deleteRows();">
<input type="button" name="delTable" value="Usuń tabele" onclick="deleteTable();">

</form>

</body>
</html>



Komentarze: