breezy
breezy

Reputation: 1918

How to get value of data attribute with jquery

I want to be able to grab html5 attribute values and have them match the value and attribute name with the class - then hide on click.

for example data-table="sample11" should hide class="sample11" same for sample14 and any other attributes on this page

I was trying something like this but it isn't working for me - below is the way i am trying to do this - here is my fiddle http://jsfiddle.net/breezy/xq6epy39/

Any help or guidance would be helpful. Thanks!

<div data-table="sample11">
  <a href="#">when i click this 'hide this' in sample11 should hide</a>
</div>

<div class="sample11">

  hide this
</div>


<div data-table="sample14">
   <a href="#">when i click this 'hide this' in sample14 should hide</a>
</div>

<div class="sample14">

  hide this
</div>

jQuery

var sample = $('div').data("table") === "11";

sample.click(function() {

  $('.sample11').hide();

});

Upvotes: 2

Views: 616

Answers (3)

Manish Shukla
Manish Shukla

Reputation: 1365

you can use data attribute with jquery. I have modified your code

<div>
   <a href="#" class="clickme" data-table=".sample14">when i click this 'hide this' in sample14 should hide</a>
</div>

<div class="sample14">

  hide this
</div>

$(".clickme").click(function(){
  alert($(this).data("table"));
  $($(this).data("table")).hide();
})

in place of hide you can call toggle function for hide/unhide.

Upvotes: 0

madalinivascu
madalinivascu

Reputation: 32354

try:

$('div a').click(function(e) {
  e.preventDefault();
  $('.' + $(this).parent().attr('data-table')).toggle();//hide()//slideToggle()//fadeToggle()
});

http://jsfiddle.net/4Lor0md5/

Upvotes: 4

csum
csum

Reputation: 1992

You can specify attributes using []. There are several options using jquery selectors.

var sample = $('div[data-table="11"]');

sample.click(function() {

  $('.sample11').hide();

});

Upvotes: 0

Related Questions