7
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

checkboxで選択した際に、背景色を変更する。

Posted at

完成イメージは、【A-STAR フリーランス】フリーエンジニアの案件と仕事の検索条件指定欄のcheckboxです。

###html

jsのonclickイベントで背景色を変えるように実装します。

<form method="" action="">
    <label><input class="check" type="checkbox" id="hoge" onclick="chebg('hoge')" value="hoge">hoge</label>
    <label><input class="check" type="checkbox" id="hoge2" onclick="chebg('hoge2')" value="hoge2">hoge2</label>
    <label><input class="check" type="checkbox" id="hoge3" onclick="chebg('hoge3')" value="hoge3">hoge3</label>
    <div class="menu-submit">
        <input type="submit" value="送信" />
    </div>
</form>

###javascript

if文でcheckboxにチェックがついているかどうかで分岐させます。

function chebg(chkID){//タグの背景色変更
    Myid=document.getElementById(chkID);
    if(Myid.checked == true){
        Myid.parentNode.style.backgroundColor = '#CC28A8';
        Myid.parentNode.style.color = '#FFFFFF';
    }else{
        Myid.parentNode.style.backgroundColor = '#FFFFFF';//背景色
        Myid.parentNode.style.color = '#333333';//文字色
    }
}

###css
今のままだと、チェックボックスが見えていますので、cssで隠します。

.check{
    display:none;
}
7
8
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
7
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?