jQueryでフォーム部品のcheckedやselectedはpropで操作する
よく勘違いして慌てているので書いておきます。
フォーム部品のcheckedやselectedといったbool型のプロパティの操作は、propを使用する。以前はattrを使っていた記憶がありますが、それではちゃんと動いてくれないです。
いちご みかん りんご 全部
$(function () {
//全部選択もしくは解除
$('#checkAll').change(function(){
$('input.fruit').prop(
'checked',
$(this).prop('checked'));
$('select[name=fruit] option').prop(
'selected',
$(this).prop('checked'));
});
//チェックボックスの変更をリストへ反映
$('input.fruit').change(function(){
$('select[name=fruit] option[value=' + $(this).attr('value') + ']')
.prop('selected', $(this).prop('checked'));
});
//リストの変更をチェックボックスへ反映
$('select[name=fruit]').change(function() {
$('select[name=fruit] option').each(function() {
console.log($(this).attr('value'));
$('input.fruit[value=' + $(this).attr('value') + ']')
.prop('checked', $(this).prop('selected'));
});
});
});