Executing client side javascript from an asp:radiobutton control when there’s no onclientclick event

Some ASP.net controls have onclientclick events, making it easy to wire in client side javascript code – saving round trips for menial tasks.

Radio buttons seem to be missing this.

This is a way around the missing event:

(1) In your asp.net .aspx page add:

<script language=”javascript” type=”text/javascript”>

function rdChangeWithdraw_Click()
{
    var objrdChange = document.getElementById(“<%= objrdChange%>”); 
    var objrdWithdraw = document.getElementById(“<%= objrdWithdraw%>”); 
    var objtxtWithdrawalDetails = document.getElementById(“<%= objWithdrawalDetails%>”);

    if (!objrdChange) return (false); 
    if (!objrdWithdraw) return (false); 
    if (!objtxtWithdrawalDetails) return (false); 

    objtxtWithdrawalDetails.disabled = (objrdChange.checked);

    return (true);
}
</script>

for

for these radio buttons:

<asp:RadioButton runat=”server” GroupName=”ChangeWithdraw” ID=”rdChange” />
<asp:RadioButton runat=”server” GroupName=”ChangeWithdraw” ID=”rdWithdraw” />

to enable and disable this textbox

<ASP:Textbox runat=”server” ID=”txtWithdrawalDetails” Runat=”server”  />

(2) In your asp.net .aspx.cs code behing page add:
….

protected void Page_Load(object sender, EventArgs e)
{
// get rendered id’s of objects for use in client side javascript
objrdChange = this.rdChange.ClientID.ToString();
objrdWithdraw = this.rdWithdraw.ClientID.ToString();
objWithdrawalDetails = this.txtWithdrawalDetails.ClientID.ToString();
// add event handlers to radio buttons to fire client side javascript
this.rdChange.Attributes.Add(“OnClick”, “rdChangeWithdraw_Click();”);
this.rdWithdraw.Attributes.Add(“OnClick”, “rdChangeWithdraw_Click();”);

The page pre-renders the controls, assigning IDs, then in Page_load populates the server side variables embeded in the client side javascript, then the client side javscript ‘knows’ the names of the controls once rendered, and is then able to interact with the as-rendered controls at the client and without a round trip.

Advertisements