ボタンでテーブルの行を追加する

[新着] Webテンプレートを仮オープンしました



0   名前: 海老天 : 2007/05/21(月) 19:26  ID:EZMicZs0 sub-Z7
デフォルト2*2のテーブルにボタンを押したら
行を追加する方法を教えていただきたいです。
追加したカラムにはテキストフィールドも表示させたいです。

以上、宜しくお願いいたします。

1   名前: Chip : 2007/05/21(月) 19:26  ID:iXTrKUp6 sub-FV
テーブルへの行(、セル)、<input>の追加サンプルです。
<html>
<head>
<script type="text/javascript">
function addRow(){
	var T = document.getElementById('T1');
	T.insertRow(T.rows.length);
	T.rows[T.rows.length -1].insertCell(0);
	T.rows[T.rows.length -1].insertCell(1);
	var newInput1 = document.createElement('input');
	T.rows[T.rows.length -1].cells[0].appendChild(newInput1);
	var newInput2 = document.createElement('input');
	T.rows[T.rows.length -1].cells[1].appendChild(newInput2);

}
</script>
</head>
<body>
<p><input type="button" value="行追加" onclick="addRow()"></p>
<table id="T1">
<tr><td><input></td><td><input></td></tr>
<tr><td><input></td><td><input></td></tr>
</table>
</body>
</html>

2   名前: NullPo : 2007/05/21(月) 19:26  ID:Z0FHbpib sub-ii
行を追加する。
<script type="text/javascript">

function insertRow(srcElement) {

  while(srcElement && srcElement.tagName != "TBODY" && srcElement.tagName != "TABLE")
    srcElement = srcElement.parentNode;

  if(!srcElement)
    return;

  srcElement.insertRow();
}

</script>

<table>
 <tr>
  <td>あ</td>
  <td>い</td>
 </tr>
 <tr>
  <td><br></td>
  <td><input type="button" value="追加" onclick="insertRow(this)"></td>
 </tr>
</table>

テキストフィールドを表示する?
document.createElement("textarea");
かな。

3   名前: 匿名 : 2007/05/21(月) 19:26  ID:OF72WdCi sub-Cz
>>1-2
っ[結婚指輪]

蛇足ながら、
・insertRow(-1)、insertCell(-1) でも最後尾に挿入されます。文脈上、楽な方でどうぞ。
・newInput2 = newInput1.cloneNode(false) で要素をコピーできます。同じ生成過程を何度も書きたくないときに。
・HTML ならば、タグがあろうとなかろうと、table 要素は必ず tbody 要素を持ちます。tbody 要素の存在チェックが必要なのは XHTML の場合です(その場合、要素名は小文字)。

4   名前: Chip : 2007/05/21(月) 19:26  ID:iXTrKUp6 sub-FV
>3
>insertRow(-1)、insertCell(-1) でも最後尾に挿入
これは知らなかったです。便利ですね。

5   名前: 匿名 : 2007/05/21(月) 19:26  ID:uHvAKwDQ sub-kJ
>>3
> tbody 要素の存在チェック

ごめん、これに関しては私が >>2 を誤読していた。

・ボタンが thead/tfoot 要素内にある場合は table 要素の最後尾に、
・ボタンが tbody 要素内にある場合は、その tbody 要素の最後尾に、

という意図だよね。余計なことを言ってすまん。

一覧へ戻る