<a id="option1" data-id="10" data-option="21" href="#" onclick="goDoSomething(?,?);"> Click to do something </a>
I want to get the data-id
and data-option
values inside the function goDoSomething(10, 21)
I have tried to use this
reference: this.data['id']
but it did not work.
How can I do this?
The data-* attribute is a Global Attribute, and can be used on any HTML element.
The onclick event attribute in HTML works when the user clicks on the button. When the mouse clicked on the element then the script runs. Syntax: <element onclick = "script"> Attribute Value: This attribute contains a single value script that works when the mouse clicked on the element.
Use the querySelector method to get an element by data attribute, e.g. document. querySelector('[data-id="box1"]') . The querySelector method returns the first element that matches the provided selector or null if no element matches the selector in the document.
You can achieve this $(identifier).data('id')
using jquery,
<script type="text/javascript"> function goDoSomething(identifier){ alert("data-id:"+$(identifier).data('id')+", data-option:"+$(identifier).data('option')); } </script> <a id="option1" data-id="10" data-option="21" href="#" onclick="goDoSomething(this);"> Click to do something </a>
javascript : You can use getAttribute("attributename")
if want to use javascript tag,
<script type="text/javascript"> function goDoSomething(d){ alert(d.getAttribute("data-id")); } </script> <a id="option1" data-id="10" data-option="21" href="#" onclick="goDoSomething(this);"> Click to do something </a>
Or:
<script type="text/javascript"> function goDoSomething(data_id, data_option){ alert("data-id:"+data_id+", data-option:"+data_option); } </script> <a id="option1" data-id="10" data-option="21" href="#" onclick="goDoSomething(this.getAttribute('data-id'), this.getAttribute('data-option'));"> Click to do something </a>
Like this:
$(this).data('id'); $(this).data('option');
Working example: http://jsfiddle.net/zwHUc/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With