How to save data from a foreach in html in an array of Javascript

0

I'm with a project using laravel and when I get the controller data, in the view I use a foreach to recover the data sent, but I would also like each data sent to be stored in an array in Javascript to be able to operate with these.

view:

@foreach($producto as $prod)
    <tr>                          
       <td>
          <input type="text" min="1" max="100" id="precio" value="{{ $prod->precio }}" readonly="readonly">
       </td>
       <script>
           function calcular(){
               var precio = document.getElementById("precio");
               var total = precio.value;
               var array = [total]
               for ( i = 0; i < array.length; i++) {
                   var resultado = array[i];
                   console.log(resultado);   
               }
           }
      </script>
  </tr>
@endforeach 
<td>
    <button  onClick="calcular()" class="btn btn-info" id="calcular">Total</button>
</td>

At the moment of printing the array, it only saves the first data that was in the list when it should show all the data that I sent from the controller.

    
asked by Daniel Gironás 07.12.2018 в 06:31
source

3 answers

1

Your code as mentioned has several logic and concept errors

  • The ids of the html elements must have a unique ID, all your price inputs have the same 'price' id, you can generate dynamic ids or assign a generic class for them and call them by the name of the class.
  • The script where you define your calculate function can not be within a cycle, this produces that it prints and defines so many times in the final code in the browser as elements you are going through.
  • document.getElementById returns a single element, the first one it finds with the specified ID.
  • Correct calculation logic
  • So your code should correct those three points.

    <script>
       function calcular(){
           var precios = document.getElementsByClassName("precio");
           var precios_array = [];
           var total = 0;
           for ( i=0; i<precios.length; i++){
               //totalizado de precios
               total+= parseFloat(precios[i].value);
    
               //guardar los valores en un array
               precios_array.push( parseFloat(precios[i].value) );
           }
           console.log(total);
       }
    </script>
    
    @foreach($producto as $prod)
        <tr>                          
           <td>
              <input type="text" class="precio" value="{{ $prod->precio }}" readonly="readonly">
           </td>
        </tr>
    @endforeach 
    <td>
        <button  onClick="calcular()" class="btn btn-info" id="calcular">Total</button>
    </td>
    

    Make the corrections, test and tell how it went.

        
    answered by 07.12.2018 / 20:24
    source
    1

    the script should not be inside the foreach because every time it iterates it will initialize all the variables again. With this function you can add data to an array:

    <script>
        prod=[];
        var result=[];
        prod.forEach(function (item) {
             result.push(item.value);
        });
    </script>
    
        
    answered by 07.12.2018 в 18:53
    1

    If I understood well you just want to know the sum of your totals and print it, I recommend you do it from your controller, it is better to leave all calculations on the server side to avoid possible attacks and / or malfunctions by users who modify your JavaScript code , then just send the variable to the route and the samples and use as you wish:

    On your controller, after calculating the total sum:

    return view('tuVista', [
        'prod'  => $prod,
        'total' => $total,
    ]);
    

    In your view:

    <td>
        <tr>Total: {{ $suma }}</tr>
    </td>
    
        
    answered by 07.12.2018 в 19:17