I am trying to change the class name to an element when its value goes down
My view in the blade is a foreach
JavaScript
x
14
14
1
@foreach ($scaduti as $item )
2
<tr>
3
<td>{{$item->name}}</td>
4
<td>{{$item->lotto}}</td>
5
<td>{{carbonCarbon::createFromFormat('Y-m-d', $item->data_di_scadenza)->format('d-m-Y')}}</td>
6
<td>{{$item->sector->settore}}</td>
7
<td>{{$item->sector->scaffale}}</td>
8
<td id="changecolor">{{$item->sector->quantita_rimanente - $item->sector->quantita_bloccata}}</td>
9
<td>{{$item->sector->quantita_bloccata}}</td>
10
11
12
</tr>
13
@endforeach
14
I want to add a class to the td
with id “changecolor”
My script is:
JavaScript
1
9
1
var x = document.getElementById("changecolor").innerHTML;
2
var i;
3
for (i = 0; i < x.length; i++) {
4
if(x[i] <= 20){
5
document.getElementById('changecolor').className= 'changetored';
6
}
7
8
}
9
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
JavaScript
1
2
1
<td name="changecolor">{{$item->sector->quantita_rimanente - $item->sector->quantita_bloccata}}</td>
2
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:
JavaScript
1
10
10
1
var x = document.getElementsByName("changecolor");
2
var i;
3
4
for (i = 0; i < x.length; i++) {
5
if(x[i].innerHTML <= 20){
6
x[i].className = "changetored";
7
}
8
9
}
10