<...">

get data attribute value by link / button

<span class="btn btn-block btn-inverse btn-icon glyphicons home" id="changeb" data-datac="daily"><i></i>Daily</span>
            <span class="btn btn-block btn-inverse btn-icon glyphicons home" id="changeb" data-datac="1week"><i></i>1 Week</span>
            <span class="btn btn-block btn-inverse btn-icon glyphicons home" id="changeb" data-datac="monthly"><i></i>Month</span>
            <span class="btn btn-block btn-inverse btn-icon glyphicons home" id="changeb" data-datac="3Month"><i></i>3 Month</span>

jquery

$('#changeb').click(function() {

        var d = $(this).data('datac');      
        alert(d);   
} );

I need to get the value of data-datac on click event,

+4
source share
6 answers

Your code is fine, you have the same identifier for more than one element , which is invalid. The event will be bound to the first element with the given id in DOM. Use a generic class instead of id to bind an event. You can use the class selector to bind the event.

Live demo

$('.btn').click(function() {
      var d = $(this).data('datac');      
      alert(d);   
});
+11
source

This should do the trick:

var d = $(this).attr("data-datac");

, HTML, . click . . :

HTML

<span class="btn btn-block btn-inverse btn-icon glyphicons home dateChanger" id="changeb1" data-datac="daily"><i></i>Daily</span>
<span class="btn btn-block btn-inverse btn-icon glyphicons home dateChanger" id="changeb2" data-datac="1week"><i></i>1 Week</span>
<span class="btn btn-block btn-inverse btn-icon glyphicons home dateChanger" id="changeb3" data-datac="monthly"><i></i>Month</span>
<span class="btn btn-block btn-inverse btn-icon glyphicons home dateChanger" id="changeb4" data-datac="3Month"><i></i>3 Month</span>

Javascript

$(".dateChanger").click(function () {
    var d = $(this).attr("data-datac");
    alert(d);
});
+6

...

 var data_value = $(this).attr("data-datac");
+1

id. .

+1

, attr jquery,

$('.home').on('click', function() {

    var d = $(this).attr('data-datac');      
    alert(d);   
});

F.Y.I

id's , , class ,

0

var d=$(this).attr('data-datac');
0

All Articles