1

i´m traying to extract data from my array and append this data to span.

i´m working with laravel and blade

first i´m doing loop to get data from one array and create div and span in this div:

@foreach ($status as $sta)
            <div class="col-md-3">
                <span class="font-weight-bold">{{ $sta }}:</span><span class="porcentaje ml-2"></span>
            </div>
        @endforeach

after i´m doing loop in jquery to other array that contain value for status:

<script>
        let total = {!! json_encode($totalCall) !!};
        
        $.each(total, function(valor, indice) {
            $(".porcentaje").text(valor);
        });
        
    </script>

total it´s array that contain this values:

[3, 3, 4, 3]

but when i do text in my span i´m getting this:

AUSENTE:3
CONFIRMADA:3
NUEVA:3
NULA:3

this it´s differents status and i need append this data in this status. I don´t know that i´m doing wrong.

Thanks for help me and read me. Sorry for my english

scorpions78
  • 553
  • 4
  • 17
  • `$(".porcentaje")` selects _all_ the elements with that class across the whole document, so you are setting the text content for all of them each time. Use https://api.jquery.com/eq/ to only pick the element matching your each index variable. – CBroe Oct 14 '21 at 10:02
  • 1
    You are updating `span id ='porcentaje'` by looping `total`. First time you set its text as `3`, then `3`, `4` and lastly again to `3`. So Its text is `3` – navnath Oct 14 '21 at 10:03
  • @navnath thaks for your response. How i can to do this¿? – scorpions78 Oct 14 '21 at 10:06
  • thanks for your response, but i´m creating any span with this class in @foreach and i have all status in this for-each and i need value in this status. not set one to one – scorpions78 Oct 14 '21 at 10:08
  • @scorpions78 you just need to do `$(".porcentaje").eq(indice).text(valor);` – navnath Oct 14 '21 at 10:59
  • @navnath set value only last element – scorpions78 Oct 14 '21 at 11:01
  • @scorpions78 Do you got the solution. Or else what is the intention behind using js to set total? – navnath Oct 14 '21 at 11:02

1 Answers1

0

If the statuses and the totals all correspond, which it looks like they do, then why have two separate loops? Just output the totals as you go through your statuses?

@php $i = 0; @endphp
@foreach($status as $sta)
    <div class="col-md-3">
        <span class="font-weight-bold">{{ $sta }}:</span><span class="porcentaje ml-2">{{ $totalCall[$i] }}</span>
    </div>
    @php $i += 1; @endphp
@endforeach
Giles Bennett
  • 1,509
  • 1
  • 12
  • 15