Here is the code I am using to create a toggle switch instead of radio buttons, and it works great:
.switch
{
display: block;
float: left;
-moz-border-radius: 6px;
-webkit-border-radius: 6px;
border-radius: 6px;
font-weight: bold;
text-transform: uppercase;
background: #eee;
border: 1px solid #aaa;
padding: 2px;
box-shadow: inset 0 2px 5px rgba(0,0,0,0.2);
margin-left: 20px;
}
.switch input[type=radio]
{
display: none;
}
.switch label
{
display: block;
float: left;
padding: 3px 6px;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
border-radius: 5px;
color: #aaa;
cursor: pointer;
}
.switch label:hover
{
text-shadow: 0 0 2px #fff;
color: #888;
}
.switch label.checked
{
background: #8fc800;
color: #eee;
text-shadow: 0 -1px 1px rgba(0,0,0,0.5);
background: -webkit-linear-gradient(top, #8fc800, #438c00);
background: -moz-linear-gradient(top, #8fc800, #438c00);
background: -ms-linear-gradient(top, #8fc800, #438c00);
cursor: default;
}
Here is the HTML code for the switch:
<div class="switch">
<input type="radio" name="weekly_new" id="weekSW-0" <?=$yes_checked?> value="Yes" />
<label for="weekSW-0" id="yes">ON</label>
<input type="radio" name="weekly_new" id="weekSW-1" <?=$no_checked?> value="No" />
<label for="weekSW-1" id="no">OFF</label>
</div>
And here is the jQuery code:
<script>
$(".switch label:not(.checked)").click(function(){
var label = $(this);
var input = $('#' + label.attr('for'));
if (!input.prop('checked')){
label.closest('.switch').find("label").removeClass('checked');
label.addClass('checked');
input.prop('checked', true);
}
});
$(".switch input[checked=checked]").each(function(){
$("label[for=" + $(this).attr('id') + "]").addClass('checked');
});
</script>
I want to have a different color for when No is selected as opposed to yes - red for no, green for yes. Can this be done with the current code?
I tried to assign IDs to the labels and style them accordingly:
.switch label.checked #yes { blah blah }
But this rendered the style useless. Any suggestions on how to achieve this with the existing code?
I've created a fiddle for easier editing:http://jsfiddle.net/aS69U/