Jin Yong
Jin Yong

Reputation: 43788

Call JavaScript function while the asp:LinkButton been clicked

Just wondering, could it be possible call a JavaScript under asp:LinkButton while it been clicked.

Example: I have the following code that I would like it to be calling a JavaScript function (test()), when it been clicked. How could I do it?

    <asp:ListView ID="lvTest" runat="server" DataSourceID="dsTest" DataKeyNames="TestID"
    OnItemCommand="lvTest_ItemCommand">
    <LayoutTemplate>
      <ul style="color:#fe8113;">
        <asp:PlaceHolder ID="itemPlaceholder" runat="server" />
      </ul>
    </LayoutTemplate>
    <ItemTemplate>
      <li>
        <asp:LinkButton runat="server" CausesValidation="true" CommandName="" CssClass="orange"
          Text='<%# Eval("TestName")%>'/>
      </li>
    </ItemTemplate>
  </asp:ListView>

Upvotes: 2

Views: 18070

Answers (4)

Dave Shaw
Dave Shaw

Reputation: 1

Adding the onclientclick="JsFunctionNameHere()" to the <asp:LinkButton> worked like a charm for me.

Upvotes: 0

Bibhu
Bibhu

Reputation: 4091

<asp:LinkButton ID= "lnkButton" runat="server" CausesValidation="true" CommandName="" CssClass="orange"
          Text='<%# Eval("TestName")%>'/>

<script language="javascript" type="text/javascript">
function test() {

 // your code goes here ..

}
</script>

In code behind file write this

protected void Page_Load(object sender, EventArgs e)
{
    lnkButton.Attributes.Add("onclick", "return test()");
}

Upvotes: 1

suryakiran
suryakiran

Reputation: 1996

You can also add the required attribute as OnClientClick on the design itself, instead of binding it in the code behind.

 <asp:ListView ID="lvTest" runat="server" DataSourceID="dsTest" DataKeyNames="TestID"
    OnItemCommand="lvTest_ItemCommand">
    <LayoutTemplate>
      <ul style="color:#fe8113;">
        <asp:PlaceHolder ID="itemPlaceholder" runat="server" />
      </ul>
    </LayoutTemplate>
    <ItemTemplate>
      <li>
        <asp:LinkButton runat="server" CausesValidation="true" CssClass="orange" OnClientClick="return test();"
          Text='<%# Eval("TestName")%>'/>
      </li>
    </ItemTemplate>
  </asp:ListView>

Now Javascript function can be added

<script language="javascript" type="text/javascript">
function test()
{
    //add the required functionality
    alert('Hi');
}
</script>

Upvotes: 2

Pranay Rana
Pranay Rana

Reputation: 176956

You need to assign id to you linkbutton for following code to work which is missing in your code.

 protected void GridView1_RowDataBond(object source, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            LinkButton btnAlertStatus = (LinkButton)e.Row.FindControl("btnAlertStatus");

                btnAlertStatus.Attributes.Add("onclick", "alert('test'); ");
        }
    }

You can attach javascript to the button control in the GridView1_RowDataBond event easily as i show in above code.

Upvotes: 1

Related Questions