LoginSignup
magmag5315
@magmag5315

Are you sure you want to delete the question?

If your question is resolved, you may close it.

Leaving a resolved question undeleted may help others!

We hope you find it useful!

JavaScriptを使用したTableの要素編集

解決したいこと

HTMLで定義したTableのtd要素をJavaScriptで編集できる画面を作成しています。
色々なサイトを検索したり、コードを打ち込んで実行させてみたのですが特定のTD要素を取得する方法が思いつかず困っています。

実装方法などがあればご教授頂きたいです。

実現したい動作

「編集」ボタンを押下するとTable内にあるtd要素の中身『input type="text" readonly value="あああ"』
を書き込める状態を実現したいです。

下記の画像からであれば、住所とメモが書き込める状態(readonlyが外れる)を実現したいです

SnapCrab_NoName_2023-7-12_16-56-40_No-00.png

該当するソースコード

<body>
	<table border="1" id="tbl">
		<tr>
			<th>名前</th>
			<th>住所</th>
			<th>メモ</th>
		</tr
		<tr>
			<td><input type="text" id="txt1" name="txt1" value="田中" readonly style="background-color:transparent; border: none;"></td>
			<td><input type="text" id="txt1" name="txt1" value="佐藤" readonly style="background-color:transparent; border: none;"></td>
			<td><input type="text" id="txt1" name="txt1" value="阿部" readonly style="background-color:transparent; border: none;"></td>
		</tr>
		<tr>
			<td><input type="text" id="txt1" name="txt1" value="大阪" readonly style="background-color:transparent; border: none;"></td>
			<td><input type="text" id="txt1" name="txt1" value="東京" readonly style="background-color:transparent; border: none;"></td>
			<td><input type="text" id="txt1" name="txt1" value="福島" readonly style="background-color:transparent; border: none;"></td>
		</tr>
		<tr>
			<td><input type="text" id="txt1" name="txt1" value="ああああ" readonly style="background-color:transparent; border: none;"></td>
			<td><input type="text" id="txt1" name="txt1" value="いいいい" readonly style="background-color:transparent; border: none;"></td>
			<td><input type="text" id="txt1" name="txt1" value="うううう" readonly style="background-color:transparent; border: none;"></td>
		</tr>
	</table>
	<button class="" onclick="editRow()">編集</button>
	
	<script>
		function editRow() {
			
		}
		
	</script>
</body>

自分で試したこと

https://www.northwind.mydns.jp/samples/table_sample1.php
上記のサイトを参考に作成しています。
ただ、上記のサイトではテーブル内に編集ボタンを配置させて、ボタンを押下すると親の要素を取得して
td要素を取ってくる仕組みなっています。
テーブル外にボタンを配置させたとき、どのようにしてtd要素を取ってくるのかがいまいちよくわかりません。

0

4Answer

特定のtd要素の編集を可能にするためには、JavaScriptを使用してDOMを操作し、対応する入力フィールドからreadonly属性を削除することができます。

const table = document.getElementById('tbl');

const rows = table.getElementsByTagName('tr');
const dataRows = Array.from(rows).slice(1);

dataRows.forEach(row => {
  const cells = row.getElementsByTagName('td');

  // Get the "Address" and "Memo" cells
  const addressCell = cells[1];
  const memoCell = cells[2];

  const addressInput = addressCell.getElementsByTagName('input')[0];
  const memoInput = memoCell.getElementsByTagName('input')[0];

  addressInput.removeAttribute('readonly');
  memoInput.removeAttribute('readonly');
});

このコードは、IDによってテーブルを取得し、データ行(ヘッダー行を除く)を繰り返し処理して、「住所」と「メモ」のセルを見つけます。それから、それらのセル内の入力フィールドにアクセスし、readonly属性を削除して編集を可能にします。

提供されたHTMLでは、すべての入力要素に同じidname属性が設定されていますが、これは無効です。HTMLの規格に準拠するために、各入力フィールドに固有のidname属性を割り当てるようにしてください。

2

先ずはurlをよみながら?F12キーを押しましょう!(操作方法がテキストでは説明困難)

body table tr td
#txt1

htmlの修正が可能なら、tr にidを付番したり、tdのidをユニークにすることをお奨めします。また、列にclassを付番すると更にスタイルシートも使えて便利になります。

0
<body>
  <table border="1" id="tbl">
    <tr>
      <th>名前</th>
      <th>住所</th>
      <th>メモ</th>
    </tr <tr>
    <td><input type="text" id="txt1" name="txt1" value="田中" readonly
        style="background-color:transparent; border: none;"></td>
    <td><input type="text" id="txt1" name="txt1" value="佐藤" readonly
        style="background-color:transparent; border: none;"></td>
    <td><input type="text" id="txt1" name="txt1" value="阿部" readonly
        style="background-color:transparent; border: none;"></td>
    </tr>
    <tr>
      <td><input type="text" id="txt1" name="txt1" value="大阪" readonly
          style="background-color:transparent; border: none;"></td>
      <td><input type="text" id="txt1" name="txt1" value="東京" readonly
          style="background-color:transparent; border: none;"></td>
      <td><input type="text" id="txt1" name="txt1" value="福島" readonly
          style="background-color:transparent; border: none;"></td>
    </tr>
    <tr>
      <td><input type="text" id="txt1" name="txt1" value="ああああ" readonly
          style="background-color:transparent; border: none;"></td>
      <td><input type="text" id="txt1" name="txt1" value="いいいい" readonly
          style="background-color:transparent; border: none;"></td>
      <td><input type="text" id="txt1" name="txt1" value="うううう" readonly
          style="background-color:transparent; border: none;"></td>
    </tr>
  </table>
  <button class="" onclick="editRow()">編集</button>

  <script>
    function editRow() {
      let fr = tbl.rows.length - 1 - 1;
      let c = tbl.rows[1].cells.length;
      console.log("ヘッダーを除いて固定する行数は上から:" + fr + " 列数は:" + c);

      let e = document.getElementsByName("txt1");

      e.forEach((e, i) => {
        if (i >= fr * c) {
          console.log(e.readOnly);
          e.readOnly ? e.readOnly = "" : e.readOnly = true
        };
      });
    };
  </script>
</body>

やったこと
1.document.getElementsByName("txt1")でNodelist
2.最下段になる条件分岐if (i >= fr * c) {
3.readOnlyの切り替えはこちらを参考にしました
e.readOnly ? e.readOnly = "" : e.readOnly = true
https://hysa.hateblo.jp/entry/20091126/readonly

困ったこと
・idが全部同じ

0

Your answer might help someone💌