Cros
Cros

Reputation: 4377

How do I trigger a BulletedList in LinkButton-mode with javascript?

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?

Upvotes: 2

Views: 2291

Answers (3)

Cros
Cros

Reputation: 4377

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

Upvotes: 1

tvanfosson
tvanfosson

Reputation: 532495

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');

Upvotes: 3

Alex Gyoshev
Alex Gyoshev

Reputation: 11977

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);
}

Upvotes: 3

Related Questions