3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

javascriptにおけるtable操作(表示と非表示の切り替えも含む)

Last updated at Posted at 2020-12-17

#1.はじめに
この記事のキモはselect要素の取得とtable要素の操作

#2.サンプルコード
htmlコード

  <select id="lng" onchange="change()">
        <option id="select">選択してください</option>
        <option id="jap">日本語</option>
        <option id="eng">English</option>
        <option id="all">全て表示</option>
    </select>
    <table id = "table"> 
        <tr>
            <th>あ</th>
            <td>い</td>
            <td>う</td>
            <td>え</td>
        </tr>
        <tr>
            <th>a</th>
            <td>b</td>
            <td>c</td>
            <td>d</td>
        </tr>
    </table>

javascriptコード

function change(){
  let ta1 = document.getElementById("lng").value;
  let table = document.getElementById("table");

  var firrow = table.rows[0];
  var secrow = table.rows[1];

  switch(ta1){
    case "日本語":
      firrow.style.display = "block";
      secrow.style.display = "none";
      break; 
    case "English":
      secrow.style.display = "block";
      firrow.style.display = "none";
      break;
    case "全て表示":
      firrow.style.display = "block";
      secrow.style.display = "block";
      break;
  }
}

#3.プロセス
①selectの値を取得

let ta1 = document.getElementById("lng").value;

②tableの値を取得
rows[*]でテーブルの列を取得するのがキモ。
そしてそれを変数に代入する。

let table = document.getElementById("table");

var firrow = table.rows[0];
var secrow = table.rows[1];


selectで取得した値をswitchでふるいにかける。
なお、cssを変更してdisplay = "block"で表示して、display = "none"で非表示にするのがキモ。

switch(ta1){
    case "日本語":
      firrow.style.display = "block";
      secrow.style.display = "none";
      break; 
    case "English":
      secrow.style.display = "block";
      firrow.style.display = "none";
      break;
    case "全て表示":
      firrow.style.display = "block";
      secrow.style.display = "block";
      break;
  }

以上。

3
2
2

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
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?