テーブルの行追加・削除 †テーブルに行を追加・削除する基本は以下のようになります。 var newtr = kaimono_table.insertRow(追加する行の番号); 追加する行の番号を-1にするとテーブルの最下行に追加されます。 セル(TD)の追加はinsertCellメソッドで作成した行オブジェクトをnewtrとすると以下のようになります。 var newtd0 = newtr.insertCell(セル番号); セル番号には0から開始して順番に作成します。 セルにデータをセットするのはinnerHTMLで作成したセルオブジェクトをnewtd0とすると以下のようになります。データはTD内にセットする値で、サンプルではボタンをセットしています。 newtd0.innerHTML = データ; 削除する時は、行(TR)を削除するだけでdeleteRowメソッドです。テーブルのオブジェクトを以下の例でobjTBLとすると以下のようになります。 objTBL.deleteRow(追加する行の番号); 以下のサンプルは左のテーブルshohin_tableのボタンをクリックするとその商品名を右のテーブルshohin_tableの最下行に追加します。右のテーブルshohin_tableのボタンをクリックするとその行を削除します。 <script type="text/javascript"> function addRow(obj){ var objTR = obj.parentNode.parentNode; var number = objTR.rowIndex; var shohin = objTR.cells[1].innerHTML; var kaimono_table = document.getElementById("kaimono_table"); var newtr = kaimono_table.insertRow(-1); var newtd0 = newtr.insertCell(0); var newtd1 = newtr.insertCell(1); var button = '<input class="button orange" value=" " name="remove" onclick="removeRow(this)" type="button" number="' + number + '">'; newtd0.innerHTML = button; newtd1.innerHTML = shohin; obj.setAttribute("class","button gray"); obj.style.filter="progid:DXImageTransform.Microsoft.gradient(startColorstr='#888888', endColorstr='#575757')"; obj.disabled=true; return; } function removeRow(obj){ var number = obj.getAttribute("number"); var objTR = obj.parentNode.parentNode; var objTBL = objTR.parentNode; if (objTBL) { objTBL.deleteRow(objTR.sectionRowIndex); } var shohin_table = document.getElementById("shohin_table"); var shohinTR = shohin_table.rows[number]; var shohinInput = shohinTR.cells[0].firstChild; shohinInput.setAttribute("class","button blue" ); shohinInput.style.filter="progid:DXImageTransform.Microsoft.gradient(startColorstr='#00adee', endColorstr='#0078a5')"; shohinInput.disabled=false; return; } </script> 各関数のパラメータとして押下されたボタンのオブジェクトを渡すためにthisをセットしています。このボタンのオブジェクトより必要なオブジェクト、値を取得します。 <div> <table> <tbody> <tr> <td valign="top"> <table id="shohin_table" class="list"> <tbody> <col width=40px> <col width=90px> <col width=350px> <tr> <th>選択</th> <th>商品名</th> <th>説明</th> </tr> <tr> <td><input class="button blue" type=button value=" " onclick="addRow(this);"></td> <td>Tシャツ</td> <td>ベーシック感ある飽きのこない柄です。生地もスーパーへヴィウエイトで、かなりしっかりしています。 </td> </tr> 以下同様に商品の行 : </tbody> </table> </td> <td width="40px"> </td> <td valign="top"> <table id="kaimono_table" class="list"> <tbody> <col width=40px> <col width=90px> <tr> <th>削除</th> <th>選択商品</th> </tr> </tbody> </table> </td> </tr> </tbody> </table> </div>
![]() ![]() Last-modified: 2015-12-02 (水) 23:13:44 (2927d)
|