Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

trigger button OnClick event from Javascript

Posted on 2011-03-24
20
Medium Priority
?
1,085 Views
Last Modified: 2012-06-27
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
Comment
Question by:minglelinch
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 5
  • 4
  • +3
20 Comments
 
LVL 52

Accepted Solution

by:
Carl Tawn earned 2000 total points
ID: 35206557
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
 
LVL 9

Expert Comment

by:jkofte
ID: 35206561
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
 
LVL 82

Expert Comment

by:leakim971
ID: 35206572
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 does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
LVL 52

Expert Comment

by:Carl Tawn
ID: 35206578
>> So, there is no way to do that with Visible = False

Erm, yes there is!
0
 
LVL 82

Expert Comment

by:leakim971
ID: 35206587
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
 
LVL 9

Expert Comment

by:jkofte
ID: 35206838
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
 
LVL 52

Assisted Solution

by:Carl Tawn
Carl Tawn earned 2000 total points
ID: 35206929
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
 
LVL 9

Expert Comment

by:jkofte
ID: 35207106
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
 
LVL 52

Expert Comment

by:Carl Tawn
ID: 35207149
Not really, because obviously you would still be sanitising and verifying your input on the server side.....wouldn't you!?
0
 
LVL 9

Expert Comment

by:jkofte
ID: 35207625
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
 
LVL 1

Author Comment

by:minglelinch
ID: 35207778
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
 
LVL 52

Expert Comment

by:Carl Tawn
ID: 35207796
You don't have to, that was purely for demonstration purposes. You can call __doPostBack('<%= Button1.UniqueID %>','') from wherever you choose.
0
 
LVL 1

Author Comment

by:minglelinch
ID: 35208176
Cool ... it works ! Many thanks !
0
 
LVL 33

Expert Comment

by:Todd Gerbert
ID: 35220853
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
 
LVL 33

Expert Comment

by:Todd Gerbert
ID: 35220867
...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
 
LVL 1

Author Comment

by:minglelinch
ID: 35257968
Really good code show. I will find a case to use it sometime. Thanks, tgerbert.
0
 
LVL 5

Expert Comment

by:Tom Knowlton
ID: 36119124
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
 
LVL 1

Author Comment

by:minglelinch
ID: 36119125
Really nice discussion. All posts are great.
0
 
LVL 1

Author Closing Comment

by:minglelinch
ID: 36119133
It works. Thanks.
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Today is the age of broadband.  More and more people are going this route determined to experience the web and it’s multitude of services as quickly and painlessly as possible. Coupled with the move to broadband, people are experiencing the web via …
Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
Sometimes it takes a new vantage point, apart from our everyday security practices, to truly see our Active Directory (AD) vulnerabilities. We get used to implementing the same techniques and checking the same areas for a breach. This pattern can re…
In this video, Percona Solutions Engineer Barrett Chambers discusses some of the basic syntax differences between MySQL and MongoDB. To learn more check out our webinar on MongoDB administration for MySQL DBA: https://www.percona.com/resources/we…

721 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question