• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1295
  • Last Modified:

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.
0
minglelinch
Asked:
minglelinch
  • 5
  • 5
  • 4
  • +3
2 Solutions
 
Carl TawnSystems and Integration DeveloperCommented:
You can call the __doPostBack() method directly passing the UniqueID of the control whos event you want to trigger.
        <asp:Button ID="Button1" runat="server" Text="Click Me" Visible="false" OnClick="Button1_Click" />
        <input type="button" value="Click Me Instead" onclick="javascript:__doPostBack('<%= Button1.UniqueID %>','')" />

Open in new window

The problem is that the __doPostBack() function will only be output if there is a control on the page that is capable of triggering a postback. If there isn't then you will need to add the following line to your Page_Load() in order to force it to be output:
ClientScript.GetPostBackEventReference(this, "");

Open in new window

0
 
jkofteCommented:
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

0
 
leakim971PluritechnicianCommented:
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

0
What Kind of Coding Program is Right for You?

There are many ways to learn to code these days. From coding bootcamps like Flatiron School to online courses to totally free beginner resources. The best way to learn to code depends on many factors, but the most important one is you. See what course is best for you.

 
Carl TawnSystems and Integration DeveloperCommented:
>> So, there is no way to do that with Visible = False

Erm, yes there is!
0
 
leakim971PluritechnicianCommented:
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

0
 
jkofteCommented:
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

0
 
Carl TawnSystems and Integration DeveloperCommented:
Markup:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" EnableEventValidation="false" %>

<!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">
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="Button1" runat="server" Text="Click Me" OnClick="Button1_Click" Visible="false" />
        <input type="button" value="Click Me Instead" onclick="javascript:__doPostBack('<%= Button1.UniqueID %>','')" />
    </div>
    </form>
</body>
</html>

Open in new window

Code-behind:
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            ClientScript.GetPostBackEventReference(this, "");
        }

        protected void Button1_Click(object sender, EventArgs e)
        {

        }
    }

Open in new window

0
 
jkofteCommented:
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.



0
 
Carl TawnSystems and Integration DeveloperCommented:
Not really, because obviously you would still be sanitising and verifying your input on the server side.....wouldn't you!?
0
 
jkofteCommented:
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. )
0
 
minglelinchAuthor Commented:
The code works well. It's like I have to click "Click Me Instead" instead of clicking the original button to make it happen.
0
 
Carl TawnSystems and Integration DeveloperCommented:
You don't have to, that was purely for demonstration purposes. You can call __doPostBack('<%= Button1.UniqueID %>','') from wherever you choose.
0
 
minglelinchAuthor Commented:
Cool ... it works ! Many thanks !
0
 
Todd GerbertIT ConsultantCommented:
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>.
0
 
Todd GerbertIT ConsultantCommented:
...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

0
 
minglelinchAuthor Commented:
Really good code show. I will find a case to use it sometime. Thanks, tgerbert.
0
 
Tom KnowltonWeb developerCommented:
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.
0
 
minglelinchAuthor Commented:
Really nice discussion. All posts are great.
0
 
minglelinchAuthor Commented:
It works. Thanks.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 5
  • 5
  • 4
  • +3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now