php – Rescue data-id from a menu

Question:

How do I change the data-id of a menu link to a modal? For example I have a menu with link1 – link2 – link3. Clicking for example on link2 opens a modal displaying the values ​​of link2. These values ​​are retrieved from the database, so I need to know what the menu's data-id is in order to pull the information corresponding to that data-id from the database.

Answer:

To get the ID you can use a JavaScript function… But you don't necessarily need to use a Data attribute, as you have the ID attribute. Then you can do what you want with it.

$(document).ready(function() {
  $('ul.menu > li').on('click', function() {
    var dataId = $(this).attr('id').replace('link-', '');

    console.log(dataId);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<ul class="menu">
  <li id="link-1"><a href="#">Link 1</a>
  </li>
  <li id="link-2"><a href="#">Link 2</a>
  </li>
  <li id="link-3"><a href="#">Link 3</a>
  </li>
</ul>
Scroll to Top