選択中のラジオボタンの背景色と枠線の色を変える

jQuery を使い、選択中のラジオボタンの背景色と枠線の色を変える方法。ラジオボタンにチェックを入れると、ラジオボタンを包んでいるlabel要素の背景色と枠線の色を変更する。背景色と枠線の色を変えることで、どのラジオボタンが選択中であるか、わかりやすくすることができる。

実装例(サンプル)

実装例(サンプル)の動作について

ラジオボタンにチェックを入れると、背景色をピンク色に、枠線の色を赤色にする。

ラジオボタンからチェックを外すと、背景色を黄色に、枠線の色をグレーにする。

実装例(サンプル)のソースコード

JavaScript

<script type="text/javascript">
<!--
jQuery( function() {
    jQuery( '#jquery-smaple-form input[name=jquery-smaple-radio]' ) . change(
        function () {
            jQuery( '#jquery-smaple-form input' ) . closest( 'label' ) . css( {
                backgroundColor: 'yellow',
                borderColor: 'gray',
            } );
            jQuery( '#jquery-smaple-form :checked' ) . closest( 'label' ) . css( {
                backgroundColor: 'pink',
                borderColor: 'red',
            } );
        }
    ) . change();
} );
// -->
</script>

CSS

<style>
<!--
#jquery-smaple-form {
    padding: 10px 5px;
}
#jquery-smaple-form input {
    margin: 5px 5px 15px 5px;
    cursor: pointer;
}
#jquery-smaple-form label {
    margin: 5px;
    padding: 5px 10px;
    border: 1px solid gray;
    border-radius: 10px;
    background-color: yellow;
    font-size: 15px;
    color: #303030;
    cursor: pointer;
}
-->
</style>

HTML

<form id="jquery-smaple-form">
    <p>
        <label>
            <input type="radio" name="jquery-smaple-radio" checked="checked" />
            ラジオボタン1
        </label>
        <label>
            <input type="radio" name="jquery-smaple-radio" />
            ラジオボタン2
        </label>
        <label>
            <input type="radio" name="jquery-smaple-radio" />
            ラジオボタン3
        </label>
    </p>
</form>

スポンサード リンク

カテゴリー: API, JavaScript, jQuery, フォーム パーマリンク