Question

I have a problem with an Image Button and its onmouseover action.

In my ASPX file I have something like:

<script type="text/javascript">
    function dosth() {
        document.getElementById("btnload").click();
    }
</script>

...

<asp:Panel ID="pnUp" Height="200px" runat="server"></asp:Panel>

...

<asp:Button ID="btnload" runat="server" OnClick="btnload_Click"
    Visible="false" />

...

And in my ASPX .cs file something like:

ImageButton btnImg = new ImageButton();

protected void Page_Load(object sender, EventArgs e)
{
    btnImg.ID = "btnImg";
    btnImg.ImageUrl = "images/imgbutton.png";
    btnImg.CssClass = rblSize.SelectedValue.ToString();
    btnImg.Attributes.Add("OnMouseOver", "dosth();");
    pnUp.Controls.Add(btnImg);
}

protected void btnload_Click(object sender, EventArgs e)
{
    // stuff to do
}

But this doesn't work.

Do you know how to run C# function in onmouseover action. The JavaScript function dosth() is executing, but still it doesn't run the click function.

Was it helpful?

Solution

When referencing ID's of ASP.NET server controls via JavaScript, you must use the ClientID attribute of the control. The ClientID attribute outputs the full client side ID of the control.

This should work:

<script type="text/javascript">
    function dosth() {
        document.getElementById('<%=btnload.ClientID%>').click();
    }
</script>

OTHER TIPS

Do you have any JavaScript errors?

I think your problem is that you are using the wrong id to lookup the <img> tag in your JavaScript.

In ASP.NET, the client-side id is automatically generated to ensure it is unique.

You have two options:

Option 1: Set ClientIDMode to Static in your btnload definition.

<asp:Button ID="btnload" runat="server" ClientIDMode="Static"
    OnClick="btnload_Click" Visible="false" />

This way, the client-side id of btnload will be "btnload".

Option 2: Change your JavaScript to insert the generated client-side id.

<script type="text/javascript">
function dosth() {
    document.getElementById('<% this.btnload.ClientId %>').click();
}
</script>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top