LoginSignup
0
0

More than 1 year has passed since last update.

【コピペで使う】選択可能テーブル

Posted at

ジャカジャーン!

See the Pen 選択可能テーブルデモ by mugentaishibyo (@mugentaishibyo) on CodePen.

こんなカンジで、レコードをクリックしたら反転して、
Form要素の子要素にコピーも出来るテーブルを作りました。

使い方
1 JQueryを使える状態にしておく。
2 選択可能にしたいTable要素に 「table-selectable」クラスを指定する。

以上!

Form要素に連携したい場合は、以下も行ってください。
1 Table要素に「data-sl-formclass」属性を追加して、適当な値を指定する。
2 td要素に「data-value」属性を追加して、適当な値を指定する。
3 Form要素に1で指定した値と同じ名前のクラスを指定する。
4 3でクラスを指定したForm要素以下にある子要素にdata-value属性を追加して、
 2で指定したdata-value属性と同じ値を指定する。

…特に色を変えたり出来るほどに作り込んでるわけではないので、
自分のソースコードにコピペした後は適当に改造してあげてください。

ソースコード

index.html
<!DOCTYPE html>
<head>
	<script type="text/javascript" src="js/selectable.js"></script>
	<link rel="stylesheet" href="css/selectable.css"/>
	<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" ></script>
	<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
</head>
<body>
	<table data-sl-formclass="data_holder" class="table-selectable table w-75">
		<thead>
			<tr>
				<th class="w-25">ヘッダ列</th>
				<th>項目1</th>
			</tr>
		</thead>
		<tbody>
			<tr>
				<th>th要素1</th>
				<td data-value="col1" >td要素1</td>
			</tr>
			<tr>
				<th>th要素2</th>
				<td data-value="col1" >td要素2</td>
			</tr>
		</tbody>
	</table>
	<form class="data_holder" method="post">
		<input type="text" readonly data-value="col1">
	</form>
</body>
selectable.css
.table-selectable tbody tr:hover td{
    background-color:azure;
}
.table-selectable tbody tr.selected td{
    background-color: aquamarine;
}
selectable.js
//HTMLが読み込み終わった後に実行
$(function () {
    //選択可能テーブルの要素をクリックした時のイベント
    $('.table-selectable tbody').find('tr').on('click',
        function () {
            //すべてのtr要素の選択を解除
            var selected_row_bf = $(this).parent().children('tr.selected');
            selected_row_bf.toggleClass('selected');

            //対象のtr要素を選択
            $(this).toggleClass('selected');

            //連携先Form要素の取得
            var form_class = $(this).parents('table').attr('data-sl-formclass')
            //取得に失敗した場合は処理終了
            if (typeof form_class == "undefined") return;

            //取得したidを持つform要素を検索
            var form = $('.' + form_class);

            //選択したテーブルの情報をInput要素の同名クラスへコピー
            $(this).children('td').each(function (index, element) {
                //data-name属性の値を取得して、同じ属性値のフォームへコピー
                var data_value = 'input[data-value=\"' + element.getAttribute('data-value') + '\"]';
                form.find(data_value).val(element.textContent);

            });
        }
    )
});
0
0
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0