Link to home
Start Free TrialLog in
Avatar of minglelinch
minglelinch

asked on

trigger button OnClick event from Javascript

I have a asp:button defined and set its Visible="false".  Is it possible for me to invoke OnClick event of this button from a javacript function on this page? I need to do it. Thanks.
ASKER CERTIFIED SOLUTION
Avatar of Carl Tawn
Carl Tawn
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
let me explain;

when you set visible=false, it is a server side property of ASP.NET and that way, the control WILL NOT BE CREATED in the server side. So, there is no way to do that with Visible = False

Alternate solution: use CSS display:none

<asp:Button Style="display: none" ID="btnHdnTest" runat="server" Text="0" />

Open in new window


and on onClientClick event of another ASP.NET button, use this script:

<script type="text/javascript">
        function DeleteFromBasket(BasketLineId,CampaignId)
        {
            <%=this.Page.ClientScript.GetPostBackEventReference(this.btnHdnTest, "", False)%>;
        }
</script> 

Open in new window

If you hide it with Visible="false" the button are not rendered on the page.
You may let it visible BUT hide it's container (a div for example) :

<div style="display:none"></div><asp:Button ID="Button1" runat="server" Text="I'm hidden" Visible="true" /></div>

Open in new window


Now use :
document.getElementById("<%= Button1.ClientID %>").click();

Open in new window

>> So, there is no way to do that with Visible = False

Erm, yes there is!
Test page :

<%@ Page Title="Page d'accueil" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<script runat="server">

    void Page_Load(Object sender, EventArgs e)
    {
        Button1.Click += new EventHandler(this.GreetingBtn_Click);
    }

    void GreetingBtn_Click(Object sender,
                           EventArgs e)
    {
        Button clickedButton = (Button)sender;
        clickedButton.Text = "...button clicked...";
        clickedButton.Enabled = false;

        GreetingLabel.Visible = true;
    }

</script>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
<script language="javascript" type="text/javascript">
    window.onload = function () {
        document.getElementById("<%= Button1.ClientID %>").click();
    }
</script>
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<div style="display:none"></div><asp:Button ID="Button1" runat="server" Text="I'm hidden" Visible="true" /></div>
<asp:Label ID="GreetingLabel" runat="server" Visible="false" Text="Hello World!" />
</asp:Content>

Open in new window

hello carl_tawn,

I just tested to make sure your solution works. I apologise if I am still wrong, but I was not able to create the postback event for your code. I even added another button (which is display:none) so it can form dopostback function, but still I received error "Invalid Postback or Callback argument". So, I am still not sure if __doPostBack can be called for an element that is not rendered in HTML.

Can you send us a working code for your solution so we could all benefit with minglelinch :).

anyway here is the code that is not working.


<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
        function funct() {
            __doPostBack('<%= Button1.ClientID%>', '');
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button Visible="false" ID="Button1" runat="server" Text="Button" />
        <input id="Button2" type="button" value="button" onclick="funct();" />

        <br />
        <asp:Literal ID="Literal1" runat="server"></asp:Literal>
    </div>
    </form>
</body>
</html>

Open in new window


VB:

Partial Class _Default
    Inherits System.Web.UI.Page

    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        Me.Literal1.Text = "Clicked"
    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Me.Page.ClientScript.GetPostBackEventReference(Me, "")
    End Sub
End Class

Open in new window

SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ok, you will have to set EnableEventValidation="false" at the top of the page. You just forgot to mention that in your first post I think.
The question is would disabling Event Validation create problems or security risks for the application.



Not really, because obviously you would still be sanitising and verifying your input on the server side.....wouldn't you!?
Of course I would, also I haven't seen EnableEventValidation="false" cause any problems so far.

Anyway both options seem to be a solution and thanks carl_tawn for the new info. I really didn't know that could be done with an element that is not rendered. And my first comment was not a response to yours. Actually if you look at the time we were writing at the same time. So, I'm sorry if I have offended you.

(Just to Inform about the issue: disabling event validation will let your textbox to be posted with insecure content like "<script>alert('test')</script>". if you enable it, you will receive an error. But you still can control your data in the server side with that method. )
Avatar of minglelinch
minglelinch

ASKER

The code works well. It's like I have to click "Click Me Instead" instead of clicking the original button to make it happen.
You don't have to, that was purely for demonstration purposes. You can call __doPostBack('<%= Button1.UniqueID %>','') from wherever you choose.
Cool ... it works ! Many thanks !
One other option, is to put the code that does the "work" in a separate method.  Then in the Click EventHandler you can just call that method - this gives you the option of calling that method from other locations, to do the same work as would be done if the button were clicked.

I'm not entirely sure this will be useful to you, but you can then also call that method from JavaScript in the client browser.

On the server-side, include "using System.Web.Services;". The hidden button's click event handler just calls the DoSomeStuff() method. The DoSomeStuff() method does the actual work - it is marked with the WebMethod attribute, and is public & static (both necessary to call it from client-side JavaScript).

using System;
using System.Web.Services;

public partial class _Default : System.Web.UI.Page
{
	protected void invisibleButton_Click(object sender, EventArgs e)
	{
		// Instead of doing anything directly in the
		// button's click event handler, call the
		// DoSomeStuff() method
		DoSomeStuff();
	}

	[WebMethod]
	public static int DoSomeStuff()
	{
		// Put whatever you have now in the buton's
		// click event handler here
		Random random = new Random();

		return random.Next(0, 10);
	}
}

Open in new window


In the markup...include an <asp:ScriptManager>, your <asp:Button visible=false>, and add three JavaScript functions. One JavaScript function will call the server-side method, the second will be called when the server-side method completes, and the third will be called in the event of an error. In this example the JavaScript function visibleButton_Click calls the server-side method DoSomeStuff() (use PageMethods.NameOfServerSideMethod in JavaScript to call a server-side method). You can call the JavaScript function visibleButton_Click by any means you like, in this example I used an HTML <input type="button"> to execute it.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
	
</head>
<body>
    <form id="form1" runat="server">
    <div>
		<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" />
		<asp:Button ID="invisibleButton" runat="server" Text="Invisible Button" OnClick="invisibleButton_Click" Visible="false" /><br />
		<button id="visibleButton" onclick="visibleButton_Click()">Click Me</button>
    </div>
    </form>
	<script type="text/javascript" language="javascript">
		function visibleButton_Click() {
			// Disable the button, so it's not clicked a second time
			document.getElementById('visibleButton').disabled = true;
			// Call the server-side method from javascript
			PageMethods.DoSomeStuff(visibleButton_ClickSucceeded, visibleButton_ClickFailed);
		}

		function visibleButton_ClickSucceeded(result, userContext, methodName) {
			// Show the results
			alert('Server Side Method Succeeded, Result: ' + result);
			// Re-enable the button
			document.getElementById('visibleButton').disabled = false;
		}

		function visibleButton_ClickFailed(error, userContext, methodName) {
			// show the error
			alert('Server Side Method Failed: ' + error);
			// Re-enable the button
			document.getElementById('visibleButton').disabled = false;
		}
	</script>
</body>
</html>

Open in new window


If the <asp:Button id="invisibleButton"> is never shown, and your only purpose for this button is to execute some server-side code, then you don't even need to include the <asp:Button>.
...that above method, though, isn't really what you asked for since it doesn't cause a PostBack, which means you can't do all the same things you can with carl_tawn's suggestion - like Response.Redirect().

Though you could return a URL, and use window.location.href to work around that particular problem - I'm sure there are other issues that aren't occurring to me right now.

<%@ Page Language="C#" %>
<%@ Import Namespace="System.Web.Services" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
	[WebMethod]
	public static string DoSomeStuff()
	{
		return "http://www.google.com/";
	}
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
	
</head>
<body>
    <form id="form1" runat="server">
    <div>
		<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" />
		<button id="visibleButton" onclick="visibleButton_Click()">Click Me</button>
    </div>
    </form>
	<script type="text/javascript" language="javascript">
		function visibleButton_Click() {
			document.getElementById('visibleButton').disabled = true;
			PageMethods.DoSomeStuff(visibleButton_ClickSucceeded, visibleButton_ClickFailed);
		}

		function visibleButton_ClickSucceeded(result, userContext, methodName) {
			document.getElementById('visibleButton').disabled = false;
			window.location.href = result;
		}

		function visibleButton_ClickFailed(error, userContext, methodName) {
			alert('Server Side Method Failed: ' + error);
			document.getElementById('visibleButton').disabled = false;
		}
	</script>
</body>
</html>

Open in new window

Really good code show. I will find a case to use it sometime. Thanks, tgerbert.
I've requested that this question be deleted for the following reason:

This question has been classified as abandoned and is closed as part of the Cleanup Program. See the recommendation for more details.
Really nice discussion. All posts are great.
It works. Thanks.