I am trying to implement a grid with radio button selector. When the radio button is clicked, the row is set to a different color. Also, when a radio is selected in the grid, it needs to see if there was a previously selected radio button so that it could change the color set.
<script type="text/javascript">
var lastSelectedId = '';
function rowSelected(rdoButton) {
if (rdoButton.id != lastSelectedId) {
rdoButton.parentNode.parentNode.origClassName =
rdoButton.parentNode.parentNode.className;
rdoButton.parentNode.parentNode.className = 'rowSelected';
if (lastSelectedId != '') {
var lastRadioButton = document.getElementById(lastSelectedId);
lastRadioButton.parentNode.parentNode.className =
lastRadioButton.parentNode.parentNode.origClassName;
}
}
lastSelectedId = rdoButton.id;
}
</script>
<table>
<tr class="rowOdd">
<td>
<input type="radio" name="rdoGrpName" id="rdoId1" onclick="rowSelected(this);" />
</td>
<td>Blah</td>
</tr>
<tr class="rowEven">
<td>
<input type="radio" name="rdoGrpName" id="rdoId1" onclick="rowSelected(this);" />
</td>
<td>Blah</td>
</tr>
</table>
I was wondering how I could remove the dependency on a global variable lastSelectedId to be able to track if there is a selected item? My initial idea is to save it to a dummy variable in the body object. like use this.
function rowSelected(rdoButton) {
var mainBody = document.getElementByNames('body');
if (rdoButton.id != mainBody[0].lastSelectedId) {
// ....
}
}
I was wondering if this is the right strategy for this. Also to make the code really unobstrusive, I need to add the event handler for the onload to initialize the global variable.