Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting data-* attribute for onclick event for an html element

<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?

like image 266
zkanoca Avatar asked Nov 17 '13 11:11

zkanoca


People also ask

Can data -* attribute contain HTML tags?

The data-* attribute is a Global Attribute, and can be used on any HTML element.

What is the onclick attribute in HTML?

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.

How do I select an element by a data attribute?

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.


2 Answers

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 image 168
Krish R Avatar answered Sep 25 '22 06:09

Krish R


Like this:

$(this).data('id'); $(this).data('option'); 

Working example: http://jsfiddle.net/zwHUc/

like image 28
CD.. Avatar answered Sep 24 '22 06:09

CD..