OpenGL97
OpenGL97

Reputation: 289

asp.net button - JS click does not work

I am trying to call from JS to C# function. I can not use ajax. I have tried to create a ASP.NET button when it clicked it calls the C# function and call the click function from JS:

On HTML:

<asp:Button runat="server" ID="UploadButton" OnClick="Upload_Click" />

JS:

alert("Before CLICK");
document.getElementById("UploadButton").click();
alert("After CLICK");

ASP.NET:

protected void Upload_Click(object sender, EventArgs e)
{
    //CODE
}

The problem is that the click event from JS does not working. I have tried to write after the first line of the JS code an alert to see if the code rich to that line but I can only see "After CLICK".

I have seen this answer: Button's .click() command not working in Chrome But I did not quite get this.

Upvotes: 1

Views: 3240

Answers (2)

Dgan
Dgan

Reputation: 10295

try this

In ASP.net When Page Renders it Will change it somthing like 'containerName...YourButtonName' So Using ClientID you will get actual ID of Button.

document.getElementById('#<%= UploadButton.ClientID %>').click();

Or You can Use ClientIDMode="Static" which will rendered same ID what you wrote in Your .aspx

<asp:Button runat="server" ID="UploadButton"
 ClientIDMode="Static" OnClick="Upload_Click" />

Upvotes: 0

Amit Joki
Amit Joki

Reputation: 59292

You should set the ClientIDMode to Static

<asp:Button runat="server" ID="UploadButton" ClientIDMode="Static" OnClick="Upload_Click" />

Otherwise, it will have some randomized id, generated by ASP.NET, setting the CLientIDMode to Static, you're saying ASP.NET not to meddle with your ids and keep them intact.

Other option would be to use the ClientID property which will have the value of the automatically generated id like

document.getElementById('<%= UploadButton.ClientID %>').click();

Upvotes: 1

Related Questions