0

I have the following issue. I'm generating multiple data from db and each item has a "delete" btn which has a "data-entryid" attribute with the entry id number.

I want to pass the data attribute of each item when i click the trash icon but with the current js code i only get the first entry's id.

Here's my html btn code where "entry-num" the entry id generated from db:

<a href="#" id="dlt-btn" data-entryid="{entry-num}" class="btn btn-danger delete">
   <i class="far fa-trash-alt"></i>
</a>

And here's my js code in which i'm trying (for now) to pass the value in console:

$("#dlt-btn").click(function(){
 var entryId = $(this).data("entryid");
 console.log(entryId);
});
Harrys R.
  • 37
  • 11

5 Answers5

3

The id global attribute defines a unique identifier (ID) which must be unique in the whole document. Its purpose is to identify the element when linking (using a fragment identifier), scripting, or styling (with CSS).

Use class instead of id:

$(".delete").click(function(){
  var entryId = $(this).data("entryid");
  console.log(entryId);
});
Mamun
  • 66,969
  • 9
  • 47
  • 59
1

Use Class instead of Id Because its unique or generated id

0

Seeing as the data is being generated after the page has loaded, you should try event delegation. Something like:

$('#someParentElement').on('click', '.deleteButtonClass', function(){
 var entryId = $(this).data("entryid");
 console.log(entryId);
});
Gerry Blackmon
  • 335
  • 1
  • 2
  • 9
0

You can use simply like this use class instead id and change accordingly

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $(".dlt-btn").click(function(){
 var entryId = $(this).data("entryid");
 alert(entryId);
});
});
</script>
</head>
<body>
<a href="#" data-entryid="value" class="btn btn-danger delete dlt-btn">
   <i class="far fa-trash-alt">ddd</i>
</a>
</body>
</html>
Vishnu Chauhan
  • 301
  • 2
  • 12
0

if you do not want to use class and id Attributes.

$("a").on('click',function(){
    var entryId = $(this).data("entryid");
    console.log(entryId);
});