Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery select by data- value that is a variable

I'm having trouble applying answers from similar questions to my situation and I think it is because the value I'm looking for is a variable and not a constant string like most others.

I have a variable activeSlide equal to the active slide: 1, 2, or 3. I want the button whose data-dir = activeSlide to show bold text but I can't seem to select the button based on the data- value. I can select an exact slide number with:

$('btns [data-dir=2]')... 

But replacing 2 with activeSlide or #{activeSlide} isn't yielding any results. I'm about to re-write all my code with classes instead of the data- that is confusing me! Before I do that would someone mind showing me how I can select the button whose data-dir=activeSlide ?

html:

<div class='btns'>
  <button data-dir='1'>1</button>
  <button data-dir='2'>2</button>
  <button data-dir='3'>3</button>
</div>
like image 680
twinturbotom Avatar asked Jan 14 '23 20:01

twinturbotom


2 Answers

Try concatenating the value into the selector string.

$('.btns [data-dir="'+activeSlide+'"]')
like image 50
Musa Avatar answered Jan 17 '23 17:01

Musa


if "btns" it is a class, shouldn't it be $('.btns [data-dir=2]')?

like image 42
Pedro Borges Avatar answered Jan 17 '23 17:01

Pedro Borges