LoginSignup
74
77

More than 5 years have passed since last update.

jQueryで全選択・全解除はprop使う

Last updated at Posted at 2013-07-10

attr使ったら動きが変だった

attrじゃないかと思って作ったら、何か変。
attr('checked','')ではなく、removeAttr('checked')を使えばおk
どうやらprop使えばいいらしい。
でもpropのが楽に書ける
詳しくはCSSは分かるけどjQueryは苦手……という人が .attr()と .prop()に親しんでくれるといいなーと思って書きました。|Ginpen.comで。

チェックされているかどうかという判定には .prop()を使う必要があります。
HTMLに書いた属性の値を扱いたいときは .attr()を、いかにもJavaScript的な事をする時は .prop()

デモ

こんな感じで使えばおkだと思う。

<div class="allCheck">
<input type="checkbox" id="allCheck01"><label for="allCheck01">全選択・全解除</label>
</div>
<div>
<input type="checkbox" id="check01"><label for="check01">アイテム01</label>
<input type="checkbox" id="check02"><label for="check02">アイテム02</label>
<input type="checkbox" id="check03"><label for="check03">アイテム03</label>
</div>
$('.allCheck input,.allCheck label').click(function(){ //全選択・全解除をクリックしたとき
    var items = $(this).closest('.allCheck').next().find('input');
    if($(this).is(':checked')) { //全選択・全解除がcheckedだったら
        $(items).prop('checked', true); //アイテムを全部checkedにする
    } else { //全選択・全解除がcheckedじゃなかったら
        $(items).prop('checked', false); //アイテムを全部checkedはずす
    }
});

上のデモとattrとコメントのコード比較

補足2013.12.04

attrメソッドの仕様がjQuery 1.9から変わったそうなので、メモ。

jQueryのバージョン attrでcheck propでcheck attrで未check propで未check
〜1.8 checked true undefined false
1.9〜 undefined true undefined false

つまり、attr / removeAttrが使えなくなったようです。
デモ:http://jsdo.it/Ituki/opoF
参考:http://blog.webcreativepark.net/2013/12/04-141752.html

74
77
3

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
74
77