Javascript and asp.net custom controls
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'm 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 ID = ctl00_ContentPlaceHolder1_Material_1_RadioButton
how can this javascript code find the Radio Button controls?
<script type="text/javascript">
$(document).ready(function() {
if (document.getElementById("1_RadioButton").checked) {
$("#1_other").hide();
}
});
</script>
Below 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>
a source to share
If this code is in an .aspx file, use <% = MyRadioButton.ClientID%> in its place, and the ASP.NET renderer will correctly render the ID for you.
Update: For example:
<script type="text/javascript">
$(document).ready(function() {
if ($get("<%= MyRadioButton.ClientID %>").checked) {
$("#1_other").hide();
}
});
</script>
a source to share
I wrote a post on how to do this :
So, say that you have control over the label on your page:
The generated html output and the id of that control might look like this:
<span id="ctl00_ContentPlaceHolder1_Label1"></span>
Unfortunately the generated ct100_ContentPlaceHolder1_Label1 id will not always be the same from build build. So trying to select it like this:
$("#ct100_ContentPlaceHolder1_Label1").hide();
will eventually break and it won't hide the label control.
The trick is to use ASP.NET inside the jQuery Selector. Label1.ClientID will return the generated ID every time. We combine ASP.NET and jQuery into one by following these steps:
$("#<%= Label1.ClientID %>").hide();
This will give the generated Label Control ID every time.
a source to share