0

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>
2
  • 1
    Please use proper jQuery event handling methods, not inline event handlers set via onclick attributes. Commented Jan 27, 2023 at 8:36
  • As above, if you had correctly separated your markup from your js, this would be available. Surprisingly, none of the suggested answers show how to add a basic click handler. learn.jquery.com/events/event-basics Commented Jan 27, 2023 at 8:52

4 Answers 4

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);
}
Sign up to request clarification or add additional context in comments.

Comments

0

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>

Comments

0

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>

Comments

0

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>

`

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.