Anil Kumar Anil Kumar - 4 years ago 237
HTML Question

Assign href of anchor tag

I want to assign href of Anchor tag using JavaScript.

<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="AnchorTRY.aspx.cs" Inherits="AnchorTRY" %>

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">

<a id="anchr" runat="server"> </a>
<script type="text/javascript">
if (System.Web.HttpContext.Current.Session["Email"] == null && System.Web.HttpContext.Current.Session["uid"] == null)
{
document.getElementById("anchr").setAttribute('href', "User Login.aspx");
document.getElementById("anchr").innerText = "Create Your Own Package";
}
else {
document.getElementById("anchr").setAttribute('href', "Cities.aspx");
document.getElementById("anchr").innerText = "Add to Your Package";
}
</script>

</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder2" Runat="Server">
</asp:Content>

Answer Source

Change you code to this,

    <script type="text/javascript">
       function setHref() {
            var flag = <% 
            if (System.Web.HttpContext.Current.Session["Email"] == null && System.Web.HttpContext.Current.Session["uid"] == null)
            {
              response.write("true");
            }
            else
            {
              response.write("false");
            }
            %>;

            if(flag == true)
            {
                document.getElementById("anchr").setAttribute('href', "User Login.aspx");
                document.getElementById("anchr").innerText = "Create Your Own Package";
            }
            else {
                document.getElementById("anchr").setAttribute('href', "Cities.aspx");
                document.getElementById("anchr").innerText = "Add to Your Package";
            }
       }
   </script>

In the code we are assigning the output of your server-side code to a JavaScript variable 'flag' and according to its value JavaScript code will assign the href attribute.

And we have placed this code in to a JavaScript function, we will call it when document loads, so that it will change 'href' of anchor properly otherwise the code couldn't access anchor tag before it loads.

Call the function in body tag like this,

<body onload="setHref();">

Hope it works, let me know if you want more help. Thank you.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download