Recovering bank data and calculating inputs

2

Good night, I'm having a hard time recovering a data in the I recovery but I wanted the recovery to be simultaneous. I'll explain it better and as soon as I see the code, I'll understand.

include("banco/banco.php");

$prod = $conexao_pdo->prepare(" SELECT *FROM precos  "); 
$prod->execute();
$result = $prod->fetchAll(PDO::FETCH_ASSOC);

I retrieve the bank information with this querry, it returns me the following information: retail_id, retail_name, total_precos, which refers to the products.

<div class="col-sm-6">
   <div class="form-group">
      <div class="form-line">
         <select name="produto" class="form-control show-tick">
            <option value="">Produto</option>
            <?php foreach($result  as $prod){ ?>
            <option value="<?php  echo $prod['nome_precos']; ?>">
               <?php echo $prod['nome_precos']; ?></option>
            <?php } ?>
         </select>
      </div>
   </div>
</div>
<div class="col-sm-2">
   <div class="form-group">
      <div class="formline">
         <input type="text" class="form-control" value="" step="any" name="valor" readonly  placeholder="Valor Unitario">
      </div>
   </div>
</div>

This snippet of code retrieves the name of the products and put inside a select for the user to choose I am having difficulties in the following part when the user choose the name the value referring to the product name go to the input unit value. p>

<div class="col-sm-2">
   <div class="form-group">
      <div class="form-line">
         <input type="number" class="form-control"  name="quantidade"  required placeholder="quantidade">
      </div>
   </div>
</div>
<div class="col-sm-2">
   <div class="form-group">
      <div class="form-line">
         <input type="number" class="form-control"  name="total" readonly required placeholder="total">
      </div>
   </div>
</div>

This code above the user enters with the quantity of products he wants to acquire would like the value of the product of the above to be multiplied by the input quantity that the user entered and to return the total in the input. Anyone who can give a salve I thank you right away!

    
asked by anonymous 01.01.2018 / 22:47

2 answers

1

Create a listener for select and input quatidade , which are the two elements that will directly influence the result. Within the listener , you throw the values into the appropriate fields.

  

Change the total field to type="text" to accept decimals with   comma, just as it is in the valor unitário field.

See example below:

$("select[name='produto'], input[name='quantidade']").on("change input", function(){

   var prod_preco = parseInt($("select[name='produto'] option:selected").data("valor"));
   $("input[name='valor']").val( !isNaN(prod_preco) ? prod_preco.toFixed(2).replace('.',',') : '' );

   var prod_qtd = parseInt($("input[name='quantidade']").val());
   prod_qtd = isNaN(prod_qtd) ? 0 : prod_qtd ;

   var valor_tt = prod_preco*prod_qtd;

   var desconto = 50; // porcentagem de desconto
   var prod_desc = valor_tt * (desconto/100);

   valor_tt -= prod_desc;

   $("input[name='total']").val( !isNaN(valor_tt) ? valor_tt.toFixed(2).replace('.',',') : '' );

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="col-sm-6">
   <div class="form-group">
      <div class="form-line">
         <select name="produto" class="form-control show-tick">
            <option value="">Produto</option>
            <option data-valor="30" value="produto1">produto1</option>
            <option data-valor="10" value="produto2">produto2</option>
         </select>
      </div>
   </div>
</div>
<div class="col-sm-2">
   <div class="form-group">
      <div class="formline">
         <input type="text" class="form-control" value="" step="any" name="valor" readonly  placeholder="Valor Unitario">
      </div>
   </div>
</div>

<div class="col-sm-2">
   <div class="form-group">
      <div class="form-line">
         <input type="number" class="form-control"  name="quantidade"  required placeholder="quantidade">
      </div>
   </div>
</div>
<div class="col-sm-2">
   <div class="form-group">
      <div class="form-line">
         <input type="text" class="form-control"  name="total" readonly required placeholder="total">
      </div>
   </div>
</div>

Alternate selector

You can use a more abbreviated mode in the selector using match with event handler :
$("select, input").on("change input", function(e){

   // aqui eu só detecto alterações em input ou select com os nomes
   // "produto" ou "quantidade"
   if(e.target.name.match(/[produto|quantidade]/)){
      var prod_preco = parseInt($("select[name='produto'] option:selected").data("valor"));
      $("input[name='valor']").val( !isNaN(prod_preco) ? prod_preco.toFixed(2).replace('.',',') : '' );

      var prod_qtd = parseInt($("input[name='quantidade']").val());
      prod_qtd = isNaN(prod_qtd) ? 0 : prod_qtd ;

      var valor_tt = prod_preco*prod_qtd;

      var desconto = 50; // porcentagem de desconto
      var prod_desc = valor_tt * (desconto/100);

      valor_tt -= prod_desc;

      $("input[name='total']").val( !isNaN(valor_tt) ? valor_tt.toFixed(2).replace('.',',') : '' );
   }

});
    
02.01.2018 / 00:01
1

You could use the strategy of sending the data to the server, doing the calculations there and returning a new page. But definitely this is no longer a good practice (I do not know if it was a day), since you can do this with javascript.

You can use an event called change that is triggered when an element suffers some change. Since this varies according to the type of input. For example, to select the event will be triggered when the user chooses an option, and already for an input field, with type number, for example, will be triggered when the field contents are changed and the field loses focus. All of this is very well explained in the previous link (change) and html standard .

Returning to your case you can use a natively javascript approach, although you might choose to use the jquery response, since since you're using bootstrap, you're probably using the jquery lib. But anyway here is another way to do. Basically, I put the basic code of the necessary html and soon after I put the javascript code. As I'm not checking if the document has already loaded, this should ensure that all the hmtl has already loaded before executing the code in javascript. No more the code is commented enough.

<select name="produto" class="form-control show-tick">
    <option value="">Produto</option>
    <option value="11.50">produto 1</option>
    <option value="8.50">produto 2</option>
    <option value="20">produto 3</option>
</select>

<input type="number" class="form-control"  name="quantidade"  required placeholder="quantidade">
<input type="number" class="form-control"  name="total" readonly required placeholder="total">

<script>
//pegando referencia para os elementos relevantes. getElementsByName() retornará uma coleção de objetos. 
//Logo se houver apenas um será o do indice 0
var selectProduto = document.getElementsByName('produto')[0];
var inputQuantidade = document.getElementsByName('quantidade')[0];
var inputTotal = document.getElementsByName('total')[0];

//agora é preciso adicionar o evento change no selectProduto e no inputQuantidade
//isso permite refazer o calculo automaticamente quando qualquer um dos dois mudar
//Embora o evento change seja disparado de forma diferente em cada um deles.
//No select será disparado quando o usuario escolher um option
//ja no inputQuantidade será disparado quando o conteudo for modificado e o campo perder o foco

selectProduto.addEventListener('change', function (){
    atualizarTotal(calcular(selectProduto.value, inputQuantidade.value));       
});

inputQuantidade.addEventListener('change', function (){
    atualizarTotal(calcular(selectProduto.value, inputQuantidade.value));
});

//retorna o valor de preço * quantidade, ambos considerados do tipo float
//aqui você pode adicionar algumas validações
function calcular(preco, quantidade){
    var total = parseFloat(preco) * parseFloat(quantidade);
    return total;
}

//atualizar input name="total"
//aqui você poderá formatar a exibição em formato monetrio, tipo R$ ou US$
function atualizarTotal(valor){
    //como você pode perceber o valor anterirmente armazenado em inputTotal
    //será sempre sobreescrito
    inputTotal.value = valor;
}
</script>
    
02.01.2018 / 00:39