How can I prevent a user from clicking on a RadioButtonList when I need to change the selected value based on a form option using JavaScript?

Issue

How can I prevent a user from clicking on a RadioButtonList when I need to change the selected value based on a form option using JavaScript?

Background

In WorkflowGen, you can set the FORM_FIELD_READONLY parameter to lock a RadioButtonList. However, once it becomes read-only, .NET will not accept any changes updated by JavaScript. This is a .NET default behavior on read-only controls.

Solution

If you need to update a RadioButtonList client-side (using JavaScript) and not perform a post back with code-behind, you can add the following JavaScript helper function:

Consider the following RadioButtonList control:

<asp:RadioButtonList ID="TEST" runat="server" RepeatDirection="Horizontal">
<asp:ListItem Value="YES" >YES</asp:ListItem>
<asp:ListItem Value="NO" >NO</asp:ListItem>
</asp:RadioButtonList>

To lock a radio button, you can add the following JavaScript function:

<script language="javascript" type="text/javascript">
 function LockRadioButtonToDefault(what)
 {
 var RadioButtonObj = document.getElementsByName(what.id);
 for (i=0; i<RadioButtonObj.length; i++)
 {
 if (RadioButtonObj[i].nodeName == "INPUT")
 {
 if (RadioButtonObj[i].defaultChecked==true)
 { RadioButtonObj[i].checked=true; }
 else { RadioButtonObj[i].checked=false; }
 }
 }
 }
</script>

Within your JavaScript code that changes the selection of this radio button, make sure you set the button checked state as well as its defaultChecked state.

Example

document.getElementsByName("TEST")[1].checked = true;
document.getElementsByName("TEST")[1].defaultChecked = true;

In your code-behind file (aspx.cs or aspx.vb), add the following line whenever you want to have this locking mechanism enabled:

C#: this.TEST.Attributes.Add("onclick","LockRadioButtonToDefault(this)");
VB: Me.TEST.Attributes.Add("onclick","LockRadioButtonToDefault(this)"