Retrieving database data and calculating inputs

Asked

Viewed 120 times

2

good evening I’m having a hard time performing a data recovery on I recover but wanted the recovery to be simultaneous I will explain better and once you see the code you will understand.

include("banco/banco.php");

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

recover the information of the bank with this querry, it returns to me the following information id_precos, name_precos, total_precos, which are related 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 code snippet retrieves the name of the products and place within a select for the user to choose I’m having difficulties in the following part when the user choose the name the value referring to the product name go to the unit value input.

<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 above code the user enters the quantity of products he wishes to acquire would the product value la from above be multiplied by the quantity input that the user entered and return the total in the input. Who can give a cheer there I thank from now!

2 answers

1


Create a Listener to the select and the input quatidade, which are the two elements that will directly influence the result. Within the Listener, you play the values for the proper fields.

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

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>
<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>
            <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 on 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('.',',') : '' );
   }

});
  • and how do I load the unit value question to the @dvd input

  • ah yes I’ve seen my mistake here made filet

  • at the end of to divide the total by a variable $_SESSION['discount']?

  • percentage if it has to add $ , 00 in the values that are going to the fields @dvd

  • @Tuliovieira Code updated. Just put a discount value in number format.

  • only I need this value to be of the variable $_SESSION['discount']

  • blz to no aguardo @dvd

  • total stopped working

  • do not forget that I need the value of the discount comes from the variable $_SESSION['discount']

  • @Tuliovieira Change the total field to type="text"... and replace the discount line: var desconto = <?php if(empty($_SESSION['desconto'])){ echo '0';}else{ echo $_SESSION['desconto'];} ?>; // porcentagem de desconto

  • was seeing here <option value="100">100</option> this taking the value of the product and not the name when I have inserted do not know the name of the product

  • @Tulip tree You have to change the value of options by name

  • @Tuliovieira Perai who will need to adjust the code, I will update...

  • @Tulip tree Just change that part: var prod_preco = parseInt($("select[name='produto'] option:selected").text());

  • if you make this change the stick code the inputs with the product price and the total do not work

  • @Tuliovieira Take a look and run the example in the answer. It works normal. The change I made did not influence anything as it was before. I just swapped the value selection for the select text.

  • yes I understood but I did it the way it is there and nothing :/ if you want to pass the code snippet for you to see via Skype Whats.. @dvd

  • help ai @dvd not solved my problem

  • @Tulip tree There must be something else bugging the code. See in the example of the answer running the snippet, it works normal.

  • only that the product is there as value and in my code the product has a name and a value the user clicks on the name and tals the imput receives the name of the product and not the value. in the querry I made it comes the name and the value tmb but n I can make it work

  • @Tuliovieira No select value is the name of the product and the text is the value. That’s not it?

  • no value takes the product name and the text and the name tmb and the product value it do not know what to do to store and make the calculations @dvd

  • @Tulip tree I get it. That’s easy, I’ll update the answer and you take a look.

  • @Tulip tree I created an attribute data-valor where I place value... value and text is the product name.

  • Top @dvd solved my problem

Show 20 more comments

1

You could use the strategy to send the data to the server, do the calculations there and return a new page. But this is definitely no longer good practice (I don’t know if it was one day), since you can do this with javascript.

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

Returning to your case you can use a native javascript approach, although you may choose to use the jquery answer, since since you are using bootstrap, you are probably using the jquery lib. But anyway, here’s another way to do it. Basically, I put the basic html code needed and then put the javascript code. Since I’m not checking if the document has already loaded, this should ensure that all hmtl has already loaded before executing the javascript code. In addition the code is sufficiently commented.

<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>
  • only that the product input receives the product name the input value has to receive the value corresponding to the product I selected in the input with name and the price multiplication * quantidade la ta certinho and if possible put in the function calculate where you multiplied the value at the end to give the total divide it by a variable $_SESSION['discount']. @juven_v

  • This requires a new approach. The simplest would be to add an Hidden field in the form. Something like <input type="hidden" name="desconto" value="<?php echo $_SESSION['desconto'];?">, and capture it with javascript at the appropriate time. Although you have to validate it on the server. And this refers to a more appropriate solution, which is to create a function on the server to do this calculation and request it using ajax.

Browser other questions tagged

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