テーブルにインプットが複数
このようなselectが2つなのですが、
1つ目のselectに合わせて、2つ目のselectを変えたい。
加えて、他のやつと連動しないように注意したい。
国 | 言語 | |
---|---|---|
作ったもの例
codepen
https://codepen.io/klack710/pen/XWbBZGj?editors=1111
仕組み
- selectが変わると、自分と変更対象をターゲットに関数が動く
- 兄弟要素のtr内のselectを範囲として、変更対象を指定する
- 変更対象を一度全て非表示にする
- トリガーとなったvalueがついたclassを対象に、非表示を元に戻す
// 入力項目のvalueに合わせて、target_select_selectorの該当クラス以外のoptionを非表示にする function changeSelectOptionByThis(_this, target_select_selector) { // 全ての選択を外す $(_this).closest('tr').find(target_select_selector + ' option').attr("selected", false); // デフォルトを選択する $(_this).closest('tr').find(target_select_selector + ' .default').attr("selected", true); // 一度すべてを非表示にする $(_this).closest('tr').find(target_select_selector + ' option').each((index, element) => { $(element).hide(); }); // デフォルトのクラスを表示する $(_this).closest('tr').find(target_select_selector + ' .default').each((index, element) => { $(element).show(); }); // 対象となるクラスを表示する if (_this.value) { $(_this).closest('tr').find(target_select_selector + ' .' + _this.value).each((index, element) => { $(element).show(); }); } }
<table> <tr> <th>国</th> <th>言語</th> </tr> <tr> <td> <select onchange="changeSelectOptionByThis(this, '.lang')"> <option value=""></option> <option value="en">アメリカ</option> <option value="jp">日本</option> </select> </td> <td> <select class="lang"> <option value="" class="hidden"></option> <option value="" class="hidden en">英語</option> <option value="" class="hidden jp">日本語</option> </select> <td> </tr> <tr> <td> <select onchange="changeSelectOptionByThis(this, '.lang')"> <option value=""></option> <option value="en">アメリカ</option> <option value="jp">日本</option> </select> </td> <td> <select class="lang"> <option value="" class="hidden"></option> <option value="" class="hidden en">英語</option> <option value="" class="hidden jp">日本語</option> </select> <td> </tr> </table>