The reason this script doesn't work is because of you are using an user
control. Generally, .NET appends this _ct* prefix with the controls that
placed in a UserControl and UserControl placed in a page, which is to
make uniqueness among the controls present in the UserControl and in the
Page.
The solution to this problem is you have to place this script in your
code behind file's Page_Load event. Check the below code.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
String _Script = "function CheckQuestion()";
_Script += "{";
_Script += "var checkBox = document.getElementById({0});";
_Script += "alert(checkBox.checked)";
_Script += "}";
// Assume you have the RadioButton already defined
_Script = String.Format(_Script, SecurityStandard.ClientId);
Page.ClientScript.RegisterStartupScript(this.GetTy pe(),
"CheckBox_Script", _Script, true);
}
}
For your understanding, the trick part is
_Script = String.Format(_Script, SecurityStandard.ClientId);
I am just updating the ASP.NET generated control id to the script,
instead of the one it has in the design time. By using
RegisterStartupScript I am registering the script to the client.
Let me know if you have further issues with the code.
-
Vadivel Kumar
http://vadivelk.net
Note: This solution will only work in .NET 2.0, Let me know if you are
looking for .NET 1.1
tshad wrote:
I get an error when running my Javascript inside my UserControl. It works
fine if I put the UserControl Data directly in my Web Page.
The stripped down code is:
<script language=javascript>
function CheckQuestion()
{
var checkBox = document.getElementById('SecurityStandard');
alert("checkBox.checked = " + checkBox.checked);
}
</script>
Mozilla doesn't seem to have a problem, but IE gives me this error:
Error: Object required.
The object in the UserControl is:
<asp:RadioButton ID="SecurityStandard" Checked="true"
GroupName="SecurityQuestion" runat="server" Text=" Secret Question:"/>
From View Source:
<input id="_ctl0_SecurityStandard" type="radio"
name="_ctl0:SecurityQuestion" value="SecurityStandard" checked="checked"
onclick="return CheckQuestion();" />
On the page that does work:
<input id="SecurityStandard" type="radio" name="SecurityQuestion"
value="SecurityStandard" checked="checked" onclick="return CheckQuestion();"
/>
For some reason the radio buttons Name is appended with "_ctl0:" in the
UserControl and nothing is appended in the regular page.
I am used to seeing this from DataGrids, but not as a regular control on the
page.
How would I hande the Javascript in this case?
Thanks,
Tom