Ann
Ann

Reputation: 139

Unable to make data attribute work with jquery

I have three buttons. when I press button one, line x should toggle, button two, line y toggles and so on...( using html5's data attribute). Unfortunately I am unable to make this happen as I get an error saying type error: star.toggle() is not a function . my code below:

<button class= "a" data-p="x"> Button one </button> 
<button class= "a" data-p="y"> Button two </button>
<button class= "a" data-p="z"> Button three </button>


<div class = "x"> Line x </div>
<div class = "y"> Line y </div>
<div class = "z"> Line z </div>

jquery:

$(document).ready(function() {
    $('.a').on('click', function(){
         var star= $(this).attr('data-p');
         (star).toggle();
    }); 
});

Upvotes: 1

Views: 45

Answers (1)

Lucas Souza
Lucas Souza

Reputation: 371

Thats what you want to do?

See the JSFiddle: http://jsfiddle.net/nb6ypjsq/

$(document).ready(function() {
    $('.a').on('click', function(){
         var star= $(this).data('p');
         $('.' + star).toggle();
    }); 
});

Upvotes: 3

Related Questions