Styling checkboxes with jQuery

Pennywise83 picture Pennywise83 · Jun 13, 2013 · Viewed 18.9k times · Source

I need to stylize some checkboxes through jquery, but I don't want to use plugins. I just need a simple jQuery code.

I thought to use a simple list with css style.

<ul id="list">
 <li class="selected"><a id="1" href="#">1</a></li>
 <li><a id="2" href="#">2</a></li>
 <li><a id="3" href="#">3</a></li>
</ul>

In the same time i put in the code the input checkboxes hidden by css:

<input type="checkbox" id="1" name="rivista_numero" value="1" checked />    
<input type="checkbox" id="2" name="rivista_numero" value="2" />
<input type="checkbox" id="3" name="rivista_numero" value="3" />

With jquery if I click to the " link the parent li element will receive the "selected" class and the checkbox with the same ID will be checked.

Do you think that this could be a good solution? Is it possible to achieve this result with jQuery?

Answer

JP Hellemons picture JP Hellemons · Jun 13, 2013

No javascript required, just CSS http://jsfiddle.net/jphellemons/XvZY9/

HTML:

<input type="checkbox" id="c1" name="cc" />
<label for="c1"><span></span>Check Box 1</label>
<br/>
<input type="checkbox" id="c2" name="cc" />
<label for="c2"><span></span>Check Box 2</label>

CSS:

input[type="checkbox"] {
    display:none;
}
input[type="checkbox"] + label {
    color:#000;
    font-family:Arial, sans-serif;
    font-size:14px;
}
input[type="checkbox"] + label span {
    display:inline-block;
    width:19px;
    height:19px;
    margin:-1px 4px 0 0;
    vertical-align:middle;
    background:url(http://webdesigntutsplus.s3.amazonaws.com/tuts/391_checkboxes/check_radio_sheet.png) left top no-repeat;
    cursor:pointer;
}
input[type="checkbox"]:checked + label span {
    background:url(http://webdesigntutsplus.s3.amazonaws.com/tuts/391_checkboxes/check_radio_sheet.png) -19px top no-repeat;
}

for radiobutton's http://jsfiddle.net/jphellemons/XvZY9/1/

source: http://webdesigntutsplus.s3.amazonaws.com/tuts/391_checkboxes/demo.html