skip to Main Content

I am working on jquery with php,Right now i have button inside loop and i want to pass "data attribute" and want to get value,Right now i am getting "undefined",So how can i do this ?
Here is my current code

echo "<td>"."<a class='map-pop' data-id='".$employee_time['id']."' data-toggle='modal' data-target='#mapModal' onclick='viewmap();'><img src='assets/viewmap.png'></a>"."</td>";
                    
<script>
function viewmap()
{
     var ids = $(this).attr('data-id');
        alert('id is ' + ids);
}

</script>

4

Answers


  1. change your onclick to this

    onclick='viewmap(this)'
    

    and get data with jquery like this

    function viewmap(elm){
      var id = $(elm).data('id');
      alert('id is ' + id);
    }
    
    Login or Signup to reply.
  2. Pass this in onclick function and get in viewmap function and access
    You can try below code ..

    PHP

    <?php
    
    echo "<td>"."<a class='map-pop' data-id='".$employee_time['id']."' data-toggle='modal' data-target='#mapModal' onclick='viewmap(this);'><img src='assets/viewmap.png'></a>"."</td>";
             
    ?>  
    

    Script

    <script>
    function viewmap(m)
    {
         var ids = m.attr('data-id');
            alert('id is ' + ids);
    }
    
    </script>
    
    Login or Signup to reply.
  3. The problem is that you are using this inside your function viewmap but you are not sending it as a parameter from the HTML code, Change your onclick by: onclick='viewmap(this); than change the js function like bellow:

    function viewmap(e)
    {
         var ids = $(e).attr('data-id');
         alert('id is ' + ids);
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <a class='map-pop' data-id='1254' data-toggle='modal' data-target='#mapModal' onclick='viewmap(this);'>
      click here
    </a>
    Login or Signup to reply.
  4. Remove onclick attribute and change the viemap() function like this

    $(".map-pop").click(function(e) {
      e.preventDefault();
      
      let ids = $(this).data('id');
      alert(`id is ${ids}`);
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <a class='map-pop' data-id='".$employee_time['id']."' data-toggle='modal' data-target='#mapModal'><img src='assets/viewmap.png'></a>

    `

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search