Alessandro Minneci Alessandro Minneci - 3 months ago 18
ASP.NET (C#) Question

How To Call Javascript-Function on RadioButton-Selection?

This is how my RadioButtonList looks(ASP.NET):

<asp:RadioButtonList ID="RadioButtonListGutscheinArt" Visible="true" runat="server">
<asp:ListItem ID="ListItemZugAbonnement" Value="1" Selected="True" />
<asp:ListItem ID="ListItemBestellungHalbtax" Text="Bestellung Halbtax" Value="2" />
</asp:RadioButtonList>


I also created a Javascript Function called
backendClick()
which animates elements on my page....

function backendClick() {
$("#PanelPassnummer").fadeIn();
$("#textbox").animate({ height: '795px' }, "slow");
$('#Wrapper').animate({ paddingBottom: '20%' }, "slow");
$('html,body').animate({ scrollTop: $("#weiterButtonAbstand").offset().top }, "slow");
$('#weiterButtonAbstand').animate({ marginBottom: '8%' }, "slow");
}


My Goal is to execute the Function,
backendClick()
when the
ListItemBestellungHalbtax
is selected. NOT CLICKED, the function will be executed when the page is reloading, so the button is already selected when the page loaded.

Now in my C# code behind, i tried like this: (In
protected void Page_Load
)

if(RadioButtonListGutscheinArt.SelectedValue == Convert.ToString(2))
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "Callfunction", "backendClick()", true);

}


But with no success....
Any Suggestion on how to do it? Let me know if further information is required.. Thanks

Answer

When using asp controls the ID changes in the client side and that's explain why your jquery functions doesn't work. You should add ClientIDMode="Static" to your asp controls to remain with the same ID.

So try this:

<asp:RadioButtonList ID="RadioButtonListGutscheinArt" ClientIDMode="Static" Visible="true" runat="server">
      <asp:ListItem ID="ListItemZugAbonnement" ClientIDMode="Static" Value="1" Selected="True" />
      <asp:ListItem ID="ListItemBestellungHalbtax" ClientIDMode="Static" Text="Bestellung Halbtax" Value="2" />
</asp:RadioButtonList>

Now JQuery selector will work for you. try this:

$('#RadioButtonListGutscheinArt input').change(
    function(event){
        if ($(this).is(':checked') && event.target.id=="ListItemBestellungHalbtax") {
            backendClick();
        }
    });

And for invoking the function every time the page is reloading you can use:

$(document).ready(function(){
   backendClick();
   //will check the radio button every time
   $('#ListItemBestellungHalbtax').attr('checked', true);
});

Good luck.