Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get data attribute value onclick link / button

Tags:

html

jquery

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

the jquery is

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

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

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

like image 351
Steve Bals Avatar asked Dec 12 '13 10:12

Steve Bals


2 Answers

Your code is fine you have same id for more then one element which is not valid. The event will be binded to first element with given id in the DOM. Use common class instead of id to bind the event. You can use class selector to bind the event.

Live Demo

$('.btn').click(function() {
      var d = $(this).data('datac');      
      alert(d);   
});
like image 129
Adil Avatar answered Sep 27 '22 21:09

Adil


You can get attribute values of an element using the attr in jquery like

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

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

F.Y.I

If you will use id's as selector you can only get one element while on a class you can get reference all the elements containing that class

like image 35
HTTP Avatar answered Sep 27 '22 19:09

HTTP