I am trying to use JavaScript to update the checked status of a radio button on a site managed by a large company. Here’s the issue – the page has duplicate IDs and names for the two related radio buttons and they reside in the cell of a row of an unnamed table. I want to select the first one. Thanks for any help.
Below is the basic html
<table cellspacing='0' cellpadding='0' border='0'>
<tr>
<td>
<img alt='spacer' src='../Images/blank.gif' width='10' height='1' border='0' />
</td>
<td id='A-Q1_0200-1' valign='top'>
<font size='-1'>
<input type='radio' name='Q1_0200' id='Q1_0200' value='1' onclick='FormChanged()'
class='bodyInput' />
</font>
</td>
<td colspan='1' valign='top' id='A-Q1_0200-1-T'>
<font size='-1'>
Yes
</font>
</td>
<td>
<font size='-1'>
</font>
</td>
<td id='A-Q1_0200-2' valign='top'>
<font size='-1'>
<input type='radio' name='Q1_0200' id='Q1_0200' value='2' checked='checked' onclick='FormChanged()'
class='bodyInput' />
</font>
</td>
<td colspan='1' valign='top' id='A-Q1_0200-2-T'>
<font size='-1'>
No
</font>
</td>
</tr>
</table>
Below are the various javascript examples I’ve tried to update the radio to select the first radio option.
document.getElementById('A-Q1_0200-1').Q1_0201.checked='checked';
document.getElementById('A-Q1_0200-1').radio[0].checked=TRUE;
document.getElementById('Q1_0200').checked=TRUE
document.getElementById('Q1_0200').checked=’TRUE
You cannot have duplicate IDs and expect
getElementById()to work. ID means “identity” and each ID needs to be unique. That is why your 3rd and 4th examples failed.The following code will select the parent
<td>by it’s id, then it will select the first descendantinputand set thecheckedproperty.