JS to add online checkbox

Asked

Viewed 54 times

0

I don’t know much about you, so I need some help. I have a page that generates a form with a quotation map, in columns (each supplier in a column), and I need the user to select the checkbox he make the sum online because each supplier has a minimum value to be able to authorize the billing.

The point is that the script uses the name=days[] in all checkboxes, and I need a different name for each vendor, this I can do by php using variables, but how I do so js can create multiple codes by taking the name of my checkbox variable ?

Part of php code that generates the result and the checkbox:

        #Monta listagem de valores referente ao produtos

        //selecionando os valores    
        $sqlValores = "SELECT v.total, id_precos, v.preco
                       FROM tbl_cot_precos AS v
                       WHERE id_produto = '" .$produtos['produtosCod'][$i]. "'
                       AND v.id_pedido =$id_pedido";            
        $resValores = mysql_query($sqlValores);




        while ($listaValores = mysql_fetch_array($resValores))
        {
            //exibe valores

            echo '<td align="right"><input type="text" style="font-family: Tahoma; font-size: 10px" size="12" name="valor_unit" value="' .number_format($listaValores[2], 2, ',', '.'). '" readonly="readonly"></td>
                  <td align="right"><input type="text" style="font-family: Tahoma; font-size: 10px" size="12" name="valor_total" value="' .number_format($listaValores[0], 2, ',', '.'). '" readonly="readonly"></td>
                  <td style="display:none;"><input type="hidden" name="produto_id_'.$listaValores[1].'" value="'.$listaValores[1].'"></td>
                  <td style="display:none;"><input type="hidden" name="pedido" value="'.$id_pedido.'"></td>
                  <td><input type="checkbox" class="dias" name="dias[]" value="'.$listaValores[0].'"></td>';    

        }


        $i++;
        #Fim monta listagem de preços referente ao produtos

    echo '</tr>';

js making the online checkbox sum that are clicked:

    <script type="text/javascript">
        jQuery(function() {
        $(document).ready(function() {
           $(".dias").change(function() {
              var total = $('input[class="dias"]:checked').get().reduce(function(tot, el) {
              return tot + Number(el.value);
           }, 0);
           $('#resultado').val(total);
         });
       });
     });
    </script>
  • You need to create many code and want to store where? First in array or directly in the database?

  • Where does the identification of each supplier enter into it?

  • The suppliers' data and the prices of each one are already in the comic book, in this routine I only demonstrate to the user, the issue is that as he can buy products from several suppliers, I need him to make the sum and confront with the minimum purchase value information. So you need JS to be able to get the checkbox ID of each vendor, the checkbox ID name I can for example assign the vendor code, but how JS will know that name ?

  • Here in the code I can add the vendor code in the BD <td><input type="checkbox" class="days" name="dias_$id_vendor[]" value="'. $listaValores[0]. '"></td>';

  • You want the check name to assign the code?

2 answers

0

I made a basic example for you to analyze

Look at you:

I created a vector called: codigo which will store only the codes

When clicking, it sums up the totals and displays in place

Then you can take the example and see if it helps you

Follow the code below:

var codigo = []

$('.dias').on('change', function(){
      
      var values = 0.00;
      let id = $(this).closest('tr').find( '.id' ).text()
      var total = $('input[class="dias"]:checked').get().reduce(function(tot, el) {
              return tot + Number(el.value);
           }, 0);
      $('span').text( 'Soma total: '+total ) 
      let _id = codigo.indexOf( id )
      if( $(this).is(':checked') ) {
         if( ( _id == -1 ) ) {
            codigo.push( id )
         }
      }else{
        codigo.splice( _id, 1 )  
      }
      
      console.log( 'codigos', codigo )
      
      
    
      
 })
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>

<span></span>

<table>
  <thead>
     <tr>
        <th>Valor</th>
        <th>Id</th>
        <th></th>
     </tr>
  </thead>
  <tbody>
  <tr>
         <td class="valor">200</td> 
         <td class="id">1</td> 
         <td><input type="checkbox" class="dias" name="dias[]" value="200"></td>  
  </tr>
  <tr>
         <td class="valor">300</td>  
         <td class="id">2</td> 
         <td><input type="checkbox" class="dias" name="dias[]" value="300"></td>  
  </tr>
  <tr>
         <td class="valor">600</td>  
         <td class="id">3</td> 
         <td><input type="checkbox" class="dias" name="dias[]" value="600"></td>  
  </tr>
  </tbody>
  </table>
        

0

You can create an object with the sums for each different vendor. Say you put in name of each checkbox a different supplier:

<input type="checkbox" class="dias" name="dias_f1[]" value="5">
<input type="checkbox" class="dias" name="dias_f2[]" value="2">
<input type="checkbox" class="dias" name="dias_f1[]" value="4">
<input type="checkbox" class="dias" name="dias_f2[]" value="1">

Note that in each checkbox above there is a differentiation, where f1 and f2 would be the id’s of each vendor coming from PHP:

name="dias_$id_fornecedor[]"

This allows you to assemble a Javascript object with the sum of each checkbox checked by separating the id’s from the vendors. Let’s say you checked all the checkboxes above, it will result in an object like this:

fornecedores = {
   f1: 9,
   f2: 3
}

With this object in hand you can check the values of each object entry by the id of each vendor (f1, f2 as an example).

Your code will look like this:

$(function(){
   $(".dias").change(function(){

      var fornecedores = {};
      $('input.dias:checked').each(function(){
         var id_fornecedor = this.name.match(/dias_(.+?)\[\]/)[1];
         if(fornecedores[id_fornecedor]){
            fornecedores[id_fornecedor] += +this.value;
         }else{
            fornecedores[id_fornecedor] = +this.value;
         }
      });
      
      var total = $('.dias:checked').get().reduce(function(tot, el) {
         return tot + Number(el.value);
      }, 0);
      $('#resultado').val(total);
   });
});

Testing:

$(function(){
   $(".dias").change(function(){

      var fornecedores = {};
      $('input.dias:checked').each(function(){
         var id_fornecedor = this.name.match(/dias_(.+?)\[\]/)[1];
         if(fornecedores[id_fornecedor]){
            fornecedores[id_fornecedor] += +this.value;
         }else{
            fornecedores[id_fornecedor] = +this.value;
         }
      });
      console.log(fornecedores); // remova esta linha
      var total = $('.dias:checked').get().reduce(function(tot, el) {
         return tot + Number(el.value);
      }, 0);
      $('#resultado').val(total);
   });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table border="1">
   <tr>
      <td align="right"><input type="text" style="font-family: Tahoma; font-size: 10px" size="12" name="valor_unit" value="' .number_format($listaValores[2], 2, ',', '.'). '" readonly></td>
      <td align="right"><input type="text" style="font-family: Tahoma; font-size: 10px" size="12" name="valor_total" value="' .number_format($listaValores[0], 2, ',', '.'). '" readonly></td>
      <td style="display:none;"><input type="hidden" name="produto_id_'.$listaValores[1].'" value="'.$listaValores[1].'"></td>
      <td style="display:none;"><input type="hidden" name="pedido" value="'.$id_pedido.'"></td>
      <td><input type="checkbox" class="dias" name="dias_f1[]" value="3"></td>
   </tr>
   <tr>
      <td align="right"><input type="text" style="font-family: Tahoma; font-size: 10px" size="12" name="valor_unit" value="' .number_format($listaValores[2], 2, ',', '.'). '" readonly></td>
      <td align="right"><input type="text" style="font-family: Tahoma; font-size: 10px" size="12" name="valor_total" value="' .number_format($listaValores[0], 2, ',', '.'). '" readonly></td>
      <td style="display:none;"><input type="hidden" name="produto_id_'.$listaValores[1].'" value="'.$listaValores[1].'"></td>
      <td style="display:none;"><input type="hidden" name="pedido" value="'.$id_pedido.'"></td>
      <td><input type="checkbox" class="dias" name="dias_f2[]" value="2"></td>
   </tr>
   <tr>
      <td align="right"><input type="text" style="font-family: Tahoma; font-size: 10px" size="12" name="valor_unit" value="' .number_format($listaValores[2], 2, ',', '.'). '" readonly></td>
      <td align="right"><input type="text" style="font-family: Tahoma; font-size: 10px" size="12" name="valor_total" value="' .number_format($listaValores[0], 2, ',', '.'). '" readonly></td>
      <td style="display:none;"><input type="hidden" name="produto_id_'.$listaValores[1].'" value="'.$listaValores[1].'"></td>
      <td style="display:none;"><input type="hidden" name="pedido" value="'.$id_pedido.'"></td>
      <td><input type="checkbox" class="dias" name="dias_f1[]" value="5"></td>
   </tr>
   <tr>
      <td align="right"><input type="text" style="font-family: Tahoma; font-size: 10px" size="12" name="valor_unit" value="' .number_format($listaValores[2], 2, ',', '.'). '" readonly></td>
      <td align="right"><input type="text" style="font-family: Tahoma; font-size: 10px" size="12" name="valor_total" value="' .number_format($listaValores[0], 2, ',', '.'). '" readonly></td>
      <td style="display:none;"><input type="hidden" name="produto_id_'.$listaValores[1].'" value="'.$listaValores[1].'"></td>
      <td style="display:none;"><input type="hidden" name="pedido" value="'.$id_pedido.'"></td>
      <td><input type="checkbox" class="dias" name="dias_f2[]" value="9"></td>
   </tr>
</table>
<input id="resultado">

Remarks:

  • jQuery(function() { and $(document).ready(function() { is the same thing. Don’t repeat.
  • That selector $('input[class="dias"]:checked') can thus be simplified $('input.dias:checked').
  • Thanks, but come on.... forgive me if I let any detail go by.But still the result element is adding up all checkboxes, regardless of name.

  • It generated the different names, see: td><input type="checkbox" class="days" name="dias_9[]" value="300"></td></tr> td><input type="checkbox" class="days" name="dias_6[]" value="300"></td></tr> Where 6 and 9 are od ids of each supplier

  • see : http://simpleprice.com.br/financeiro/view_mapa_cotacao_soma.php?id=000001

Browser other questions tagged

You are not signed in. Login or sign up in order to post.