'this' keyword causing some problem (ASP.NET and Javascript)

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • btreddy
    New Member
    • Oct 2008
    • 83

    'this' keyword causing some problem (ASP.NET and Javascript)

    In my web page I have a linkbutton with onClientClick event as show below.
    Code:
    <asp:LinkButton ID="lnkbtn" Text="Click" runat="server" OnClientClick="dosomething(this.Text)"></asp:LinkButton>
    And I've defined the function as shown below in the head section of the webpage

    Code:
    function dosomething(ObjCntxt) 
    { 
      var textval = ObjCntxt;
      alert(textval); 
    }
    When I run the page and click on the LinkButton I'm getting the message 'undefined'.

    I request you all kindly solve my problem.

    Thanks & Regards,

    BTR.
    Last edited by Frinavale; Nov 26 '10, 02:37 PM. Reason: Fixed code tags. Also improved upon grammar and spelling.
  • Frinavale
    Recognized Expert Expert
    • Oct 2006
    • 9749

    #2
    In JavaScript, there is no "Text" property for a hyperlink (which is what a LinkButton rendered as).

    For example, your LinkButton:
    <asp:LinkButt on ID="lnkbtn" Text="Click" runat="server" OnClientClick=" dosomething(thi s.Text)"></asp:LinkButton>

    Will be rendered as this in HTML:
    <a id="lnkbtn" name="lnkbtn" href="javascrip t:__doPostback( 'lnkbtn','');" onclick="dosome thing(this.Text )">Click</a>

    Since there is no "Text" property for a hyperlink, pass this.innerHTML to the JavaScript method "dosoemthin g" instead. The innerHTML property will pass whatever is within the opening <a> and closing </a> tags....which is your Text.

    Like this:
    <asp:LinkButt on ID="lnkbtn" Text="Click" runat="server" OnClientClick=" dosomething(thi s.innerHTML)"></asp:LinkButton>

    -Frinny
    Last edited by Frinavale; Nov 26 '10, 02:44 PM.

    Comment

    Working...