Willie
Willie

Reputation: 123

Trying to make selector dynamic with javascript/jquery

Hello stackoverflow: I am trying to make the $('.TextBoxColors-') part of my code dynamic.
I am looking for the i variable in the for-loop to assign this value depending on the if.
I have tried many things like $('.TextBoxColors-${i}'), $('.TextBoxColors-').value(i) as in $('.TextBoxColors-').value(i).css('background-color', 'green'),
but nothing works so far.

This is the javascript/jquery:

let timeArray   = ["9","10", "11", "12", "13", "14", "15", "16", "17"]
let currentTime = parseInt(moment().format("H"));

for (i=0; i< 9; i++) {
  if (currentTime < parseInt(timeArray[i])) {
    $('.TextBoxColors-9').css('background-color', 'gray')
    $('.TextBoxColors-10').css('background-color', 'gray')
    $('.TextBoxColors-11').css('background-color', 'gray')
    $('.TextBoxColors-12').css('background-color', 'gray')
  }
  if (currentTime == timeArray[i]) {
    $('.TextBoxColors-13').css('background-color', 'Tomato')
  }
  
  if (currentTime > timeArray.indexOf("currentTime",currentTime)) {

    $('.TextBoxColors-14').css('background-color', 'green')
    $('.TextBoxColors-15').css('background-color', 'green')
    $('.TextBoxColors-16').css('background-color', 'green')
    $('.TextBoxColors-17').css('background-color', 'green')
  }
}

These are two of the divs where I want this to happen:

<!-- 2:00PM-->
<div class="input-group input-group-lg field-size Timer" >
  <div class="input-group-prepend">
      <span class="input-group-text" id="inputGroup-sizing-lg">2 PM</span>
  </div>

  <textarea type="text" class="TextBoxColors-14 form-control" aria-label="2:00 PM"     
    aria-label describedby="inputGroup-sizing-sm"></textarea>
  
  <button class="btn btn-primary" type="button" id="saveToDo-5"><i class="fa fa-floppy-o" style="font-size:18px;"></i>
  </button>
</div>

<!-- 3:00PM-->
<div class="input-group input-group-lg field-size" >
  <div class="input-group-prepend">
    <span class="input-group-text" id="inputGroup-sizing-lg">3 PM</span>
  </div>
  <textarea type="text" class="TextBoxColors-15 form-control" aria-label="3:00 AM"
    aria-describedby="inputGroup-sizing-sm"></textarea>
  
  <button class="btn btn-primary" type="button" id="saveToDo-0">
    <i class="fa fa-floppy-o" style="font-size:18px;"></i>
  </button>
</div>

Upvotes: 2

Views: 99

Answers (1)

David
David

Reputation: 219057

This is close:

$('.TextBoxColors-${i}')

But for template string literals you need to use back-ticks, not single-quotes:

$(`.TextBoxColors-${i}`)

Alternatively you can just concatenate the value to the string:

$('.TextBoxColors-' + i)

Upvotes: 2

Related Questions