DOMでテーブルへテキストボックスを動的に追加
ない場合に削除したときのエラー処理は入れてない。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>DOMでテーブルへテキストボックスを動的に追加</title> <script language="JavaScript" type="text/javascript"> <!-- var y = 0; function add() { var tr = document.createElement("tr"); tr.setAttribute("id", "tr_" + ++y); var td = document.createElement("td"); td.appendChild( document.createTextNode(y) ); tr.appendChild(td); var td = document.createElement("td"); input_text = document.createElement("input"); input_text.setAttribute("type", "text"); input_text.setAttribute("id", "inputText_" + y); td.appendChild(input_text); tr.appendChild(td); document.getElementById("tbody").appendChild(tr); } function del() { document.getElementById("tbody").removeChild( document.getElementById("tr_" + y) ); y = y - 1; } //--> </script> </head> <body onload="add();"> <div> <input type="button" value="行を追加" onclick="add();" /> <input type="button" value="行を削除" onclick="del();" /> <table border="1"> <tbody id="tbody"> <tr> <th>No</th> <th>テキストボックス</th> </tr> </tbody> </table> </div> </body> </html>