0

I'm trying to set a data-attr dinamically to 12 elements mapped by 12 buttons, so <button data-id="_id01"> will display <div data-id="_id01">,

I'm trying to select the button like $('.button').data('id').click(function() { console.log('this is the button' + data.id); })

the button and the div shall recieve the same data-, so when I click btn 01, it will toggle div01, and so on..

how ecxactly shall I reference this in the jquery?

5
  • data('id') is going to return a String. You cannot call .click() on a string Commented Feb 7, 2019 at 21:48
  • I saw some articles wich they reference as data(${current}), so the btn.dataX will handle the div.dataX, how can I do this in my case? Commented Feb 7, 2019 at 21:50
  • @Taplar it's in the jquery sorry, eddited Commented Feb 7, 2019 at 21:51
  • I have no clue what you are asking. The data attributes as you have them defined are just strings. If you want the two to affect each other, you have to write the logic to use their values to find each other. Commented Feb 7, 2019 at 21:51
  • that's what I want to do, but can't figure out how! I want btn.dataX to handle div.dataX, btn.dataY to handle div.dataY and so on! may seem stupid but I never handled jquery before so i'm having some trouble Commented Feb 7, 2019 at 21:53

1 Answer 1

1

If you are wanting to know how to use the data-id to match up the elements, you can use them with a finder or a filter.

Below is a small example of how you could match them and show just the related element.

$('button').on('click', function(e){
  $('.showMe') //find all the elements to possibly show
    .hide() //reset them to be hidden
    .filter('[data-id="'+ $(e.target).data('id') +'"]') //find the one that should show
    .show(); //show it
});
.showMe { display: none; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button data-id="_id01">Button 1</button>
<button data-id="_id02">Button 2</button>
<button data-id="_id03">Button 3</button>
<button data-id="_id04">Button 4</button>

<div class="showMe" data-id="_id01">Display 1</div>
<div class="showMe" data-id="_id02">Display 2</div>
<div class="showMe" data-id="_id03">Display 3</div>
<div class="showMe" data-id="_id04">Display 4</div>

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks it worked just fine! sorry for the trouble i'm a jquery newbie yet!!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.