tags:

views:

2534

answers:

2

How do I automatically click a Hyerlink or LinkButton using jQuery

<asp:Hyperlink id="ttt" PostBackUrl="Hut.htm">Click</asp:Hyperlink>or<asp:LinkButton id="ttt" PostBackUrl="Hut.htm">Click</asp:LinkButton>
+3  A: 

You can use the jQuery click() function without any arguments to simulate a users click.

The only tricky part with asp.net controls is the ID will be some unwieldy generated ID like ctr_00_0001 so you'll have to use a class to target the button:

<asp:LinkButton id="ttt" PostBackUrl="Hut.htm" CssClass="myButton">Click</asp:LinkButton>

and the jQuery:

$('.myButton').click();
jfar
How can I do it if this button is inside a ContentPage and using the Id and not the class?
Hitz
@Hitz id='ttt" will no longer exists when asp:LinkButton rendered. so use CssClass. and what is the problem if it is inside Content page?
Vikas
Try it at your end giving even the class. Keep the LinkButton in Content Page and access it from MasterPage using class selector. It does not get clicked.
Hitz
Master/Content Page doesn't matter as jquery runs client side. All jQuery sees is a single HTML document. Did you surround the jQuery code with a $(document).ready()?
jfar
+3  A: 

Calling the click event on a LinkButton (renders a html link) will not have much effect unless you have manually defined a javascript click event on it.

You need to execute the content in the href attribute (*javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$phContent$ttt", "", true, "", "", false, true))*):

eval($("a[id*='ttt']").attr("href"))

The code above will evaluate the javascript code in the href attribute and execute it.

ToRrEs
This does not work in many cases. If there is a return statement in the href, it fails. It also fails when "this" is used
Philippe Leybaert
That's true but I don't think ASP.NET generates a return statement or uses this in the href attribute when it renders a LinkButton.
ToRrEs