javascript and asp.net web user controls

TonyAbell picture TonyAbell · May 7, 2009 · Viewed 11.2k times · Source

I have a web user control that generates the following html on the client.

I want to reference a specific RadioButton control using JavaScript.

I am not sure how to do this as the RadioButton ID is generated by asp.net.

For example I give the RadioButton ID = 1_RadioButton

asp.net generates an ID = ctl00_ContentPlaceHolder1_Material_1_RadioButton

how can this javascript code find Radio Button controls?

    <script type="text/javascript">
        $(document).ready(function() {
            if (document.getElementById("1_RadioButton").checked) {
                $("#1_other").hide();
            }
        });    
    </script>

The following is what asp.net generates for the client.

    <input id="ctl00_ContentPlaceHolder1_Material_1_RadioButton" type="radio" name="ctl00$ContentPlaceHolder1$Material$Academic" value="1_RadioButton" onclick="javascript:$('#1_other').show('fast');" />

    <label for="ctl00_ContentPlaceHolder1_Material_1_RadioButton">Yes</label>

    <input id="ctl00_ContentPlaceHolder1_Material_2_RadioButton" type="radio" name="ctl00$ContentPlaceHolder1$Material$Academic" value="2_RadioButton" checked="checked" onclick="javascript:$('#1_other').hide('fast');" />

    <label for="ctl00_ContentPlaceHolder1_Material_2_RadioButton">No</label>

    <input id="ctl00_ContentPlaceHolder1_Material_3_RadioButton" type="radio" name="ctl00$ContentPlaceHolder1$Material$Academic" value="3_RadioButton" onclick="javascript:$('#1_other').hide('fast');" />

    <label for="ctl00_ContentPlaceHolder1_Material_3_RadioButton">Uncertain</label>

    <div id='1_other'>
         <input name="ctl00$ContentPlaceHolder1$Material$4_TextBox" type="text" value="bbb chabng" id="ctl00_ContentPlaceHolder1_Material_4_TextBox" />
   </div>

Answer

Adam Markowitz picture Adam Markowitz · May 7, 2009

If that code is in the .aspx file use <%= MyRadioButton.ClientID %> in its place and the ASP.NET rendering engine will properly render the ID for you.

Update: For example:

<script type="text/javascript">
    $(document).ready(function() {
        if ($get("<%= MyRadioButton.ClientID %>").checked) {
            $("#1_other").hide();
        }
    });    
</script>