チェックしたチェックボックスの背景の色を変更する

Ads

Result

jQuery

//チェックが入ってるのは背景色追加
$(":checked").parent().css("background","#f3f365");
//クリックイベント発火
$("input").click(function(e) {
    var t = e.target.type;
    var chk = $(this).prop('checked');
    var name = $(this).attr('name');
    チェックが入ったか入ってないかで条件分岐
    if(t == 'checkbox') {
        if(chk == true){
            $(this).parent().css('background', '#f3f365');
        } else {
            $(this).parent().css('background-color', '');
        }
        return true;
     //ラジオボタン
    } else if(t == 'radio') {
        if(chk == true){
            $("input[name=" + name + "]").parent().css("background-color","");
            $(this).parent().css("background","#f3f365");
        }
        return true;
    }
});

css

li{
    float:left;
    margin:20px;
}
label{padding:5px;}
ul{width:420px;}

html

<ul>
<li><label><input type="checkbox" />チェック1</label></li>
<li><label><input type="checkbox" />チェック2</label></li>
<li><label><input type="checkbox" />チェック3</label></li>
</ul>
<ul>
<li><label><input type="radio" name="test" />ラジオ1</label></li>
<li><label><input type="radio" name="test" />ラジオ2</label></li>
<li><label><input type="radio" name="test" />ラジオ3</label></li>
</ul>

via

jQueryでフォームのユーザビリティを強化