LoginSignup
9
5

More than 5 years have passed since last update.

行クリックでチェックボックスをON/OFFしたい

Last updated at Posted at 2017-12-14

表の中にあるチェックボックスの場合、行クリックでチェックON/OFFさせたいなんてことあると思います。

HTML
<table>
    <tr>
        <td><input type="checkbox" name="hoge" value="1"></td>
        <td>1行目</td>
    </tr>
    <tr>
        <td><input type="checkbox" name="hoge" value="2"></td>
        <td>2行目</td>
    </tr>
    <tr>
        <td><input type="checkbox" name="hoge" value="3"></td>
        <td>3行目</td>
    </tr>
</table>

行クリックでチェックボックスをトグルさせたいのでこんな処理を書いたところ、チェックボックス自体のクリックが効かなくなりました。両方のイベントでON/OFFしているので結局元に戻っているかんじ。

JavaScript
$('[name=hoge]').parents('tr').click(function(){
    $(this).find('[name=hoge]').prop('checked', !$(this).find('[name=hoge]').prop('checked'));
});

以下のようにstopPropagation()でバブリングを止めてあげたらうまくいきました。

JavaScript
$('[name=hoge]').click(function(e){
    e.stopPropagation();
}).parents('tr').click(function(){
    $(this).find('[name=hoge]').prop('checked', !$(this).find('[name=hoge]').prop('checked'));
});
9
5
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
9
5