views:

21

answers:

2

I am having links like:

<asp:HyperLink ID="lnkTitle" runat="server" CssClass="itemTitle" >
                                </asp:HyperLink>
<a id="linkOwner" runat="server" class="authorName"></a>

I am assigning the NavigateUrl from code behind at run time like:

 lnkTitle.NavigateUrl = "MyPage.aspx?id=" + userID;

 linkOwner.HRef= "MyPage.aspx?id=" + userID;

(where userID is an integer type variable)I need to access the id value from the navigate url in js file for both the cases. How access it by using jquery?Can anyone help me?

+1  A: 

You can use the selector based on id similar to CSS like this:

$('#lnkTitle')
$('#linkOwner')

See jQuery ID Selector for more info

If you want to get the id value, you can use the attr method:

$('#container a').each(function(){
   alert($(this).attr('id'));
});

The each method is used to loop over the wrapped set (what you have specified in the selector). Note that container is assumed to be the id of the element containing your links.

Sarfraz
I am not sure this is what ANP is asking ... he's talking about some data passed in the `href` of a link, not the `id` of the element ... I'll give it a try !
tsimbalar
@tsimbalar: I have posted what i could understand and you could be right; let's see what OP is upto :)
Sarfraz
A: 

Two possible options

  • In jQuery, obtain the href attribute of the generated link, and extract the userId from there : the code-behind you are typing will result in the generation of something like

<a href="MyPage.aspx?id=1234" id="SomeCrazyIDGeneratedByASP.NET">text of the link</a>

the problem here, is that the ID of the generated link may vary ... which makes the link harder to find in the page using a jQuery selector. I would suggest adding a specific CSS class to your links, for instance user-page. Then you could do something like this, I suppose :

/*extract the href attribute from the link, and get the item after the last "=" sign*/
var href = $('a.user-page').attr('href');
var split = href.split("=");
/*reverse it and take the first item (used to be last)*/
var userId = split.reverse()[0];
alert(userId);
  • The other option I usually prefer is to expose a server-side variable such as userId directly in Javascript... In order to do that, you must make userId visible from the .aspx file. Then in your .aspx file, do something like that

    <script type="text/javascript"> var userId = <%=userId%>; alert(userId); </script>

Then you can use it as any javascript variable !

tsimbalar