1

I have a button like so:

<button data-id="1" onclick="showID()">Show ID</button>

And a function:

<script>
  function showID() {
   alert(($(this).data("id")));
  }
 </script>

I just want the data-id to be shown in the alert box. I've also tried

alert(($(this).data("id")));

But again nothing...

Planty
  • 85
  • 1
  • 12
  • possible duplicate of [JavaScript - onClick to get the ID of the clicked button](http://stackoverflow.com/questions/4825295/javascript-onclick-to-get-the-id-of-the-clicked-button) – Altay Mazlum Aug 05 '15 at 09:35

5 Answers5

3

$(this) inside your click function indicates to either global in sloppy mode or undefined in strict mode.

You need to do like this:

<button data-id="1" onclick="showID(this)">Show ID</button>

<script>
  function showID(elem) {
   alert(($(elem).data("id")));
  }
 </script>
Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231
2

Try this

function showID(button) {
  alert($(button).attr('data-id'));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button data-id="1" onclick="showID(this)">Show ID</button>
Thi Tran
  • 681
  • 5
  • 11
0

Currently this will not give you the right value, your code should be this way:

<button data-id="1" onclick="showID(this)">Show ID</button>

Then

<script>
  function showID(e) {
  alert(($(e).data("id")));
  }
</script>
Luthando Ntsekwa
  • 4,192
  • 6
  • 23
  • 52
0

this doesn't work the way you are trying.

pass this on click.

Check out this fiddle.

Here is the snippet.

function showID(ele) {
  alert(($(ele).attr("data-id")));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button data-id="1" onclick="showID(this)">Show ID</button>
Shrinivas Shukla
  • 4,325
  • 2
  • 21
  • 33
0

Here there is an example, you have to pass the id to function in the button tag:

JavaScript - onClick to get the ID of the clicked button

Community
  • 1
  • 1
Asoub
  • 2,273
  • 1
  • 20
  • 33