Suraj Sharma
Suraj Sharma

Reputation: 180

How to create unique id for each html elements inside a for loop in ejs template?

$(document).ready(function() {
  $('#hiddentext').hide();

  $("#show").click(function() {
    $('#currenttext').hide();
    $('#hiddentext').show();
  });
});
<% for (var ans of quest.answers) { %>
  <div id="currenttext"><%= ans.text %></div>
  <div id="hiddentext"><%= ans.description %></div>
  <a id="show" class="btn btn-sm btn-primary">show</a>
<% } %>

I have multiple show button along with its associated HTML element inside my for loop. I am having a problem in creating unique ids for each HTML element. As for now, on clicking any of the show buttons the functionality is applied on all of the other HTML elements rather than being applied only on its associated elements. Also I have an unique _id attribute of ans i.e ans._id but I don't know to make use of it to create a unique id for my HTML tag from that and how to use that unique id inside my jQuery function.

Upvotes: 1

Views: 2206

Answers (2)

mplungjan
mplungjan

Reputation: 177691

No need for IDs

$(document).ready(function() {
  $('.hiddentext').hide(); // can be done in CSS
  $(".show").click(function() {
    $(this).prevAll('.currenttext').hide();
    $(this).prevAll('.hiddentext').show();
    // or $(this).siblings().toggle() as suggested in other post
  });
});
<% for (var ans of quest.answers) { %>
  <div>
    <div class="currenttext"> <%= ans.text %> </div>
    <div class="hiddentext"> <%= ans.description %> </div>
    <a class="show" class="show btn btn-sm btn-primary">show</a>
  </div>
<% } %>

Upvotes: 1

charlietfl
charlietfl

Reputation: 171679

Hide the hidden ones with css so they are immediately hidden on page load.

Wrap each group in a container and uses classes and traverses

$('.show').click(function() {
  $(this).siblings().toggle();
})
.hiddentext {
  display: none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <div class="currenttext">Answer #1</div>
  <div class="hiddentext">Descrip #1</div>
  <a class="show btn btn-sm btn-primary">Show</a>
</div>
<div>
  <div class="currenttext">Answer #2</div>
  <div class="hiddentext">Descrip #2</div>
  <a class="show btn btn-sm btn-primary">Show</a>
</div>
<div>
  <div class="currenttext">Answer #3</div>
  <div class="hiddentext">Descrip #3</div>
  <a class="show btn btn-sm btn-primary">Show</a>
</div>

Upvotes: 1

Related Questions