Friday 12 September 2014

Radio-buttons cannot be deselected once you've selected one.

A project I worked on recently required that a non-mandatory radio-button be deselectable. In order to implement this behaviour I used check-boxes styled to look like radio-buttons. I then added JavaScript to ensure mutual exclusive selection.

In older browsers the styling degrades (so they look like normal check-boxes) due to the lack of support for CSS pseudo-selectors.

<div class="radioboxes">
<input type="checkbox" id="radiobox1" name="group1" value="AUTHORISE" /><label for="radiobox1">Authorise</label>
<input type="checkbox" id="radiobox2" name="group1" value="DECLINE" /><label for="radiobox2">Decline</label>
<input type="checkbox" id="radiobox3" name="group1" value="OTHER" /><label for="radiobox3">Other</label>
</div>

<style type="text/css">
div.radioboxes input[type="checkbox"]:checked, div.radioboxes input[type="checkbox"]:not(:checked) {
display: none;
}

div.radioboxes input[type="checkbox"]:checked + label, div.radioboxes input[type="checkbox"]:not(:checked) + label {
position: relative;
padding-left: 21px;
}

div.radioboxes input[type="checkbox"]:not(:checked) + label::before, div.radioboxes input[type="checkbox"]:checked + label::before {
position: absolute;
left: 5px;
top: 2px;
content: " ";
display: inline-block;
background: linear-gradient(#eee, #ddd);
width: 10px;
height: 10px;
border-radius: 10px;
border: 1px solid #aaa;
box-shadow: 0px 1px 0px #eee;
}

div.radioboxes input[type="checkbox"]:checked + label::after {
position: absolute;
left: 8px;
top: 5px;
content: " ";
display: inline-block;
background: #666;
width: 6px;
height: 6px;
border-radius: 6px;
border: none;
}
</style>

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>  

<script type="text/javascript">
$(function() {
var siblings = $('.radioboxes').children('input[type="checkbox"]');
siblings.click(function() {
var e_id = $(this).attr('id');

siblings.each(function() {
if (e_id != $(this).attr('id')) {
$(this).prop('checked', false);
}

});
});
});
</script>

No comments:

Post a Comment