全体をform送信することを想定した テーブルの行 追加削除サンプル
formで送信することを想定した追加削除サンプル
by juner
HTML
<h1>テーブルの行の追加・削除</h1>
<p>[追加][削除]ボタンで行を追加削除することができます。送信の為に名前をリストで管理します。</p>
<p>[シリアライズ]ボタンを押下することで送信するときの名前と値を確認することができます。</p>
<form id="f"><table id="base">
<thead>
<tr><th></th><th>入力欄1</th><th>入力欄2</th></tr>
</thead>
<tbody>
<tr><td><button class="delete">削除</button></td><td><input type="text" name="list[].value1" value="" disabled="disabled"/></td><td><input type="text" name="list[].value2" value="" disabled="disabled"/></td></tr>
</tbody>
</table></form>
<button id="add">追加</button> <button id="serialize">シリアライズ</button>
<ul id="log"><li>name:<span class="name"></span>value:<span class="value"></span></li></ul>
CSS
html,body{
margin:0;
padding:0;
}
h1{
background-color:green;
color:white;
margin:0;
padding:0;
padding-top:0.2em;
padding-bottom:0.2em;
}
table thead th{
background-color:blue;
color:white;
padding-left:1em;
padding-right:1em;
}
table tbody tr.odd td{
background-color:silver;
}
table tbody tr.even td{
background-color:white;
}
#log li .name{
background-color:yellow;
margin-right:1em;
}
#log li .value{
background-color:silver;
}
table tbody tr:first-child,
#log li:first-child{
display:none;
}
JavaScript
(function($,undefined){
"use strict";
$(function(){
var $table = $("#base"),
$form = $("#f");
$table.find("tbody")
.on("renumber","tr:not(:first-child)",function(e,num){
var $tr = $(this),
reg = /\[.*\]/;
//numが入っていない場合は求める
num = num === undefined
? $table
.find("tbody tr:not(:first-child)")
.index(this)
: parseInt(num);
$tr
//偶奇対応
.removeClass("even odd")
.addClass( num%2==0 ? "odd" : "even")
//中の名前付き入力項目のnameの整理
.find("input[name]").each(function(){
this.name = this
.name
.replace(reg,"["+num+"]");
});
//次の行で同様のイベントを起こす
$tr.next("tr").trigger("renumber",[num+1]);
})
.on("click","button.delete",function(){
var $tr = $(this).closest("tr"),
$next = $tr.next("tr");
$tr.remove();
//もしも次の行があるなら番号の整理を行う
$next.trigger("renumber");
return false;
});
$("#add")
/**
* 行追加ボタン動作
*/
.on("click",function(e){
var $tbody = $table.find("tbody");
$tbody
.find("tr:first-child")
.clone()
.find("input[name]")
.prop("disabled",false)
.end()
.appendTo($tbody)
.trigger("renumber");
return false;
}).trigger("click");
$("#serialize")
.on("click",function(e){
var $org = $("#log li:first-child");
$("#log")
.find("li:not(:first-child)").remove().end()
.append(
$.map(
$form.serializeArray()
...