views:

942

answers:

3

Hi!

I have a BulletedList in asp.net that is set to DisplayMode="LinkButton". I would like to trigger the first "bullet" from a javascript, can this be done? And if so, how?

+3  A: 

Say you have the BulletedList as

<asp:BulletedList runat="server" ID="MyLovelyBulletedList" DisplayMode="LinkButton">
    <asp:ListItem Text="My Lovely Text 1" />
    <asp:ListItem Text="My Lovely Text 2" />
</asp:BulletedList>

... then you can fire the "onclick" event like this (cross-browser):

var links = document.getElementById('<%= MyLovelyBulletedList.ClientID %>').getElementsByTagName('a');

var targetLink = links[0];

if (targetLink.fireEvent)
{
    // IE
    targetLink.fireEvent("onclick");
}
else if (targetLink.dispatchEvent)
{
    // W3C
    var evt = document.createEvent("MouseEvents");

    evt.initMouseEvent("click", true, true, window,
     0, 0, 0, 0, 0, false, false, false, false, 0, null);

    targetLink.dispatchEvent(evt);
}
Alexander Gyoshev
The targetLink.fireEvent("onclick"); line doesn't seem to work. Using alert I can see that targetLink is the correct link, but it won't fire.
Cros
rather strange - i'll try to run it again.as a side-note, if you wish to simply make a post-back, you could call __doPostBack ('<%= MyLovelyBulletedList.ClientID %>', 0);
Alexander Gyoshev
Sadly this doesn't work for me. For some reason it just "fires" the first hyperlink on the page instead.
Cros
This solution works in Opera and Google Chrome, but not in Firefox and Internet Explorer.
Cros
+3  A: 

Similar to what Alexander indicated except that you could use jQuery to fire the event and depend on their cross-browser support rather than maintain it on your own.

$('#<%= MyLovelyBulletedList.ClientID %>')
    .contents()
    .find('a:first')
    .trigger('click');
tvanfosson
that too :) it looks so damn good with jQuery! I guess that soon we'll make John Resig chapels all over the world...
Alexander Gyoshev
and... it could be written as$('#<%= MyLovelyBulletedList.ClientID %> > a:first').trigger('click');
Alexander Gyoshev
We don't use jQuery as of now, but damn that looks smooth :)
Cros
+1  A: 

After a lot of testing it seems the only dependent way to do this is by manually firing the __doPostBack-script like so:

__doPostBack('MyLovelyBulletedList', '0');

as suggested by Alexander Gyoshev

Cros