« powrót

Dodanie wiersza do tabeli [JavaScript]

Opublikowano: 2009-10-02 , wyświetlono: 10246

Ostatnio potrzebowałem dynamicznego rozszerzania formularza, który zawierał tabelę.
Pponiżej przedstawiam rozwiązanie jakie wykorzystałem.


<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);

}
</script>

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

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

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

</fieldset>

<input type="button" name="addRow" value="Dodaj wiersz" onclick="addRowToTable();">

</form>

Przedstawiony kod w działaniu

Tabela z formularzem
tekst element input element combo


Komentarze:

bardzo przydane. dzięki za ten artykuł ;)

2012-01-14
pomoc

jak pobrać z element imput wpisane dane i ich zsumowanie w ostatniej kolumnie?

2016-08-14
ddd

dddd

2021-05-30 ddd