Skip to content
Advertisement

change color when the number goes down

I am trying to change the class name to an element when its value goes down

My view in the blade is a foreach

@foreach ($scaduti as $item )
    <tr>
       <td>{{$item->name}}</td>
       <td>{{$item->lotto}}</td>
       <td>{{carbonCarbon::createFromFormat('Y-m-d', $item->data_di_scadenza)->format('d-m-Y')}}</td>
       <td>{{$item->sector->settore}}</td>
       <td>{{$item->sector->scaffale}}</td>
       <td id="changecolor">{{$item->sector->quantita_rimanente - $item->sector->quantita_bloccata}}</td>
       <td>{{$item->sector->quantita_bloccata}}</td>


    </tr>
 @endforeach

I want to add a class to the td with id “changecolor”

My script is:

var x = document.getElementById("changecolor").innerHTML;
var i;
for (i = 0; i < x.length; i++) {
    if(x[i] <= 20){
         document.getElementById('changecolor').className= 'changetored';
        }

}

The color is applied only to the first element of the foreach and ignoring all the others.

I want to apply it to all foreach results that respect the if

Sorry for my bad English.

Advertisement

Answer

document.getElementById will always give you a single element. Most of the time the first element that it finds.

Instead of giving each element same id give them same name like

<td name="changecolor">{{$item->sector->quantita_rimanente - $item->sector->quantita_bloccata}}</td>

then use : document.getElementsByName("changecolor")

This will give all the elements with name ‘changecolor’.

You can loop through these elements and do the thing you want.

Your modified code will look something like this:

var x = document.getElementsByName("changecolor");
var i;

for (i = 0; i < x.length; i++) {
    if(x[i].innerHTML <= 20){
         x[i].className = "changetored";
        }

}
Advertisement