Radio Buttons with 2-Way Exclusivity
Inspired by Chris Coyier's article here: http://css-tricks.com/14402-radio-buttons-with-2-way-exclusivity/ Added event delegation and value switching.
by secretgspot
HTML
<table id='exclusivity-test'>
<tr>
<th></th>
<th>1</th>
<th>2</th>
<th>3</th>
<th>4</th>
<th>5</th>
</tr>
<tr>
<td>Twix</td>
<td><input type="radio" name="row-1" data-col="1"></td>
<td><input type="radio" name="row-1" data-col="2"></td>
<td><input type="radio" name="row-1" data-col="3"></td>
<td><input type="radio" name="row-1" data-col="4"></td>
<td><input type="radio" name="row-1" data-col="5"></td>
</tr>
<tr>
<td>Snickers</td>
<td><input type="radio" name="row-2" data-col="1"></td>
<td><input type="radio" name="row-2" data-col="2"></td>
<td><input type="radio" name="row-2" data-col="3"></td>
<td><input type="radio" name="row-2" data-col="4"></td>
<td><input type="radio" name="row-2" data-col="5"></td>
</tr>
<tr>
<td>Butterfinger</td>
<td><input type="radio" name="row-3" data-col="1"></td>
<td><input type="radio" name="row-3" data-col="2"></td>
<td><input type="radio" name="row-3" data-col="3"></td>
<td><input type="radio" name="row-3" data-col="4"></td>
<td><input type="radio" name="row-3" data-col="5"></td>
</tr>
<tr>
<td>Kit Kat</td>
<td><input type="radio" name="row-4" data-col="1"></td>
<td><input type="radio" name="row-4" data-col="2"></td>
<td><input type="radio" name="row-4" data-col="3"></td>
<td><input type="radio" name="row-4" data-col="4"></td>
<td><input type="radio" name="row-4" data-col="5"></td>
</tr>
<tr>
<td>Milky Way</td>
<td><input type="radio" name="row-5" data-col="1"></td>
<td><input type="radio" name="row-5" data-col="2"></td>
<td><input type="radio" name="row-5" data-col="3"></td>
<td><input type="radio" name="row-5" data-col="4"></td>
<td><input type="radio" name="row-5" data-col="5"></td>
</tr>
</table>
CSS
table {
border-collapse: collapse;
}
td, th {
border: 1px solid #ccc;
padding: 10px;
}
th:empty {
border: 0;
}
JavaScript
function buttonHandler(event, target) {
var ele = target,
col = ele.dataset.col,
row = ele.name.split('-')[1],
eleParentRow = ele.getParent('tr'),
prevCol = eleParentRow.dataset.prevCol;
ele.getParent('table').getElements('input[data-col=' + col + ']').each(function(item, index) {
if (index !== row - 1 && item.get('checked')) {
var parentRow = item.getParent('tr');
item.set('checked', false);
if (prevCol > 0) {
parentRow.getElement('input[data-col=' + prevCol + ']').set('checked', true);
parentRow.dataset.prevCol = prevCol;
} else {
parentRow.dataset.prevCol = 0;
}
}
});
eleParentRow.dataset.prevCol = col;
}
document.id('exclusivity-test').addEvents({
'click:relay(input)': buttonHandler,
'click:relay(input !> td)': function(event, target) {
var ele = target.getElement('input');
ele.set('checked', true);
buttonHandler(event, ele);
}
});