javascriptjqueryhtmljquery-data

Recovering multi id at a time


I try to put in place a system popup, why I decided to use the data attribute.

I wish that when an element has the id "popup" I recovered using the jQuery data-item value.

The data-item value has the id to display in my popup, my problem is that if I have several id popup, recovered came only 1 single id, the first in this page.

How can I do to retrieve all the popup and display ID is the corresponding value with the data-item?

<div id="boxpop">
  <div class="centered">
    <span></span>
    <div class="close-btn"></div>
  </div>
</div>
<div id="login" style="display:none;">
  Test div
</div>

<header>
  <div id="MainHeader">
    <div class="logo"></div>
    <nav id="Menu">
      <li>
        <span class="icon"></span>
        <span class="text"><a href="#" id="popup" data-item="login">Click me!</a></span>
      </li>

      <li>
        <span class="icon icone card"></span>
        <span class="text"><a href="" id="popup" data-item="test">Shop info</a></span>
      </li>
    </nav>
  </div>
</header>

<script type="text/javascript">
  $("#popup").click(function() {
    a = $("#popup").data("item");
    alert(a);

  });

  function demo(div) {
      $("#boxpop").fadeIn(500);
      $("#boxpop .centered span").empty();
      $(div).insertAfter("#boxpop .centered span").fadeIn(100);
  }
</script>
  


Solution

  • ID must be unique.

    You should use class for this, this is the correct way:

          <li>
            <span class="icon"></span>
            <span class="text"><a href="#" class="popup" data-item="login">Click me!</a></span>
          </li>
    
          <li>
            <span class="icon icone card"></span>
            <span class="text"><a href="" class="popup" data-item="test">Shop info</a></span>
          </li>
    

    And then...

    $(".popup").click(function() {
         a = $(this).data("item");
         alert(a);
    });
    

    Hope it helps.