LoginSignup
2
3

More than 5 years have passed since last update.

jQuery クリックしたテーブルの値取得

Posted at

業務でクリックしたテーブルの値を取得する必要があった為、
その方法を調べたメモ書き。

実際のソースコード

GetTableVal.html
<!DOCTYPE html>
<html>
    <head>
        <title>ジジ&ハリー</title>
        <meta charset="UTF-8" />
    </head>
    <script type="text/javascript"
            src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <body>
        <table id="friend-table" border="1" cellspacing="0" cellpadding="5" >
            <tr>
                <th hidden>No</th>
                <th>名前</th>
                <th>特徴</th>
                <th>好きな食べ物</th>
                <th>好きな遊び</th>
            </tr>
            <tr class='chara'>
                <td hidden>01</td>
                <td>ジジ</td>
                <td>目が大きい</td>
                <td>チョコバット</td>
                <td>ハリーと遊ぶ</td>
            </tr>
            <tr class='chara'>
                <td hidden>02</td>
                <td>ハリー</td>
                <td>かわいい</td>
                <td>チョコパイ</td>
                <td>空中散歩</td>
            </tr>
        </table>
    </body>
    <script type="text/javascript">
        $('.chara').on('click', function(){
            var hiddenVal = $(this).children('td')[0].innerText;
            var nameVal = $(this).children('td')[1].innerText;
            alert('No: '+ hiddenVal + ' name: '+ nameVal);
        });
    </script>
</html>

説明
①どのレコードがクリックされたか識別出来るようテーブルの<tr>タグにclass='chara'属性を付与
②var hiddenVal = $(this).children('td')[0].innerText;
 クリックされたレコードの0番目の値をjQueryオブジェクトとして取得
 そのオブジェクトのinnerTextプロパティの値を取得して変数に格納

2
3
0

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