Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using data attributes with jQuery

Tags:

I have this button:

<button type="button" class="themeChanger" data-themeValue="grid" value="Grid">
   <img src="templateImages/Icon_200.png" />                
</button>

And this jQuery:

$(".themeChanger").click(function () { 
    alert($(this).attr("data-themeValue")); 
    alert($(this).data("themeValue")); 
});

For some reason the first alert shows "grid" like it should, but the second shows undefined. Is there something stupid I'm missing?

like image 395
Adam Rackis Avatar asked Sep 29 '11 19:09

Adam Rackis


1 Answers

I think data will look on lowercases: alert($(this).data("themevalue")) //grid

or if you want to use themeValue you need to use:

edit:

I was wrong, it doesnt have anything to do with lowercases, you can use themeValue if you are having the attribute: data-theme-value then you call itwith $(element).data("themeValue")

<button class="themeChanger" data-themeValue="Theme1" data-theme-value="Theme2"></button>

$(".themeChanger").click(function() {
    var el = $(this);

    alert($(this).data("themeValue")); //Theme2
    alert($(this).data("themevalue")); //Theme1
});
like image 59
voigtan Avatar answered Oct 14 '22 21:10

voigtan