0

I have a hyperlink that's being generated dynamically. In addition I have a "p" tag that's being generated dynamically too, but it's hidden. I've attached IDs to both of them and want to use jQuery for the click event. When a user clicks on the hyperlink, it will show that only P tag above it. Normally, I would just add the ending part of the ID, but since you have two dynamic IDs generating, how would you connect them together without triggering others? Down below is a sample of my code:

<asp:ListView runat="server"...>
  <ItemTemplate>
    <p id="MsgClick" runat="server">You have click on this button></p>
    <asp:HyperLink ID="label" runat="server" NavigateURL='<%#Eval("Link")%>' Target="_blank" Text="Click Here"></asp:HyperLink>
  </ItemTemplate>
</asp:ListView>

<script type="text/javascript">
  $(document).ready(function(){
    $([id$='MsgClick']").hide();
    $("[id$='label']").on('click', function() {
      $("[id$='MsgClick']").show();
    })
  });
</script>

2 Answers 2

1

Use Class selector instead of Id:

<asp:ListView runat="server"...>
  <ItemTemplate>
    <p id="MsgClick" class="MsgClick" runat="server">You have click on this button</p>
    <asp:HyperLink ID="label" class="label" runat="server" NavigateURL='<%#Eval("Link")%>' Target="_blank" Text="Click Here"></asp:HyperLink>
  </ItemTemplate>
</asp:ListView>

<script type="text/javascript">
  $(document).ready(function(){
    $(".MsgClick").hide();
    $(".label").on('click', function() {
      $(this).prev(".MsgClick").show();
    })
  });
</script>
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. This work. What happens if the P tag is not above the link/button and it's somewhere else?
If it's not directly above the link button and say in the same container, you could find it using the parent() - just make sure to put both of them inside one container like a <div>: $(this).parent().find(".MsgClick").show();
0

You don't have to rely on id to accomplish this. jQuery provides different methods of traversing the DOM. Also, you can hide the <p> with CSS and not rely on JS.

For example:

$("a").on("click", function() {
    $(this).prev("p").show();
});

http://codepen.io/johnniebenson/pen/QELzLL

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.