Update total value with quantity

Asked

Viewed 2,019 times

2

Good guys I am with the following problem , I have a simple sales panel that shows the products, quantity, value and total value , so I choose a product appears the value of the item , the problem would be in the case how I would do so so that when I change the quantity the total value increases as much in the quantity

inserir a descrição da imagem aqui

if in quantity I put 2 in the total value would be twice the value 4,259,53 and each time adding up 1 , someone can give me a light ?

My code :

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<link rel="stylesheet" type="text/css" href="css/bootstrap.css">
<link rel="stylesheet" type="text/css" href="css/estilo.css">
<link  type="text/javascript" href="jquery.js">
<link type="text/javascript" href="post.js">
<link  type="text/javascript" href="jquery-form.js">
<body>
<form action="" method="post" enctype="multipart/form-data">
    <fieldset>
        <?php
        include ('banco.php');
        ini_set('default_charset','UTF-8');

        if($_GET){
            $id = $_GET['id_venda'];
        }

        if(isset($_POST['send'])){

            $produtos = $_POST['produtos'];
            $id_venda = $_POST['id_venda'];
            $quantidade = $_POST['quantidade'];
            $valor = $_POST['valor'];
            $valortotal = $_POST['valortotal'];

            mysql_query("INSERT INTO pedido(id, produtos, id_venda, quantidade, valor, valortotal )
            values(
                NULL,

                '{$produtos}',
                '{$id_venda}',
                '{$quantidade}',
                '{$valor}',
                '{$valortotal}'
                              );
            ");

            header("location:cabecalho.php?&id={$id} ");
        }

        ?>

    <legend style="color: #ffffff" class="btn btn-inverse">Vendas </legend>
    <?php
        ini_set('default_charset','UTF-8');
        mysql_connect('127.0.0.1','root','');
        mysql_select_db('mecanica');
        $query='Select * from produtos';
    ?>

    <label for="produtos" style="color: #000"><strong>Produto : </strong></label>
    <select name="produtos" onchange="prodValor(this.value)" style="width: 400px">

    <?php
       //execução da query
        $resultado=mysql_query($query);
        while($linha=mysql_fetch_array($resultado))
            {

                echo '<option  value="' . $linha['id_produto'] . '">' . $linha['produtos'] . '</option>';
            }
            echo '</select>';
    ?>
     </select><br><br>

        <div id="quanti">
        <label for="quantidade" style="color: #000"><strong>Quantidade :</strong> </label>
        <input style="width: 85px" type="number"  name="quantidade" id="quantidade" value="1"></br></br>
        </div>

        <div id="valor">
        <label for="valor" style="color: #000"><strong>Valor :</strong> </label>
        <input style="width: 85px" type="text"  name="valor" id="valorp"  ></br></br>
        </div>


        <div id="valortotal">
        <label for="valortotal" style="color: #000"><strong>Valor Total:</strong> </label>
        <input style="width: 85px" type="text"  name="valortotal" id="valortotal" ></br></br>
        </div>




    <div id="ocultar" style="visibility: hidden" >
    <?php
        ini_set('default_charset','UTF-8');
        mysql_connect('127.0.0.1','root','');
        mysql_select_db('mecanica');
        $query='Select * from pedido';
    ?>

    <label for="id_venda" style="color: #000"><strong>ID VENDA : </strong></label>
    <select name="id_venda" style="width: 75px">
    <?php
           $resultado=mysql_query($query);
            while($linha=mysql_fetch_array($resultado))
            {

            }
            echo '<option >' . $_GET['id_venda'] . '</option>';
            echo '</select>';
    ?>
    </select><br><br>
    </div>

    <input type="submit" class="btn btn-inverse" value="Enviar" name="send">
    <a href="listadevendas.php" class="btn btn-inverse">Cancelar</a>
    </fieldset>
    </form>


    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript">
        function prodValor(id){
           $.post("teste.php",{idVar:id},function(retorno){
                dados = retorno.split("/");
                $('#valorp').val(dados[0]);
           });
        };
    </script>


    <script type="text/javascript">
        function mostra() {
            if (document.getElementById('ocultar').style.display == 'block'){
                document.getElementById('ocultar').style.display = 'none';
            }else {document.getElementById('ocultar').style.display = 'block'}
     }
    </script>

</body>
</html>
  • See if this helps you.

  • It would be good for an excerpt of the current code, it is easier for people to help.

  • Oops, updated and posted my code I hope it gets easier to help me

3 answers

3

One solution pretty gross bad I guess that’s around.

Follows the code:

valorTeste = 2129.53;
$("#nome").change(function(){
	if($("#nome").val() == 'Teste'){
    $('#valor').val(valorTeste);
  }
});
$("#qtd").change(function(){
	if($("#nome").val() == 'Teste'){
  	qtd = $('#qtd').val();
    valor = $('#valor').val();
  	val = valorTeste * qtd;
    $('#total').val(val);
  }
});
label{
  display:block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<label>
Nome <input type="text" id="nome"/>
</label>
<label>
Qtd <input type="number" id="qtd"/>
</label>
<label>
Valor <input type="text" id="valor"/>
</label>
<label>
Valor Total <input type="text" id="total"/>
</label>
</form>

  • 2

    Hi Eric. Your solution apparently solves the author’s problem, but it’s important that you put the relevant part of the code into the answer, so it doesn’t depend solely on the link. (and you can keep the link for the person to test, of course). Just for the record, you can even put JS executable in Stack Overflow in Portuguese, that you can test here.

  • Okay. I’ll edit the answer.

3


Use the jQuery

<script type="text/javascript">
$(document).ready(function() {

 $("#ID_DA_QUANTIDADE").change(function() {
   var qtd = $(this).val();
   var valor = $("#ID_DO_VALOR").val();
   var calculo = qtd * valor;
   $("#ID_DO_VALOR_TOTAL").val(calculo);

  });
});
</script>

It would be more or less like this and you would solve your problem.

  • Alisson, I corrected the code because there was an error in the parentheses.

  • @Ivanferrer Thanks!

0

Good guys after all I tried to solve, thank you all for your help.

I got it with this code :

<script type="text/javascript">
    function id(el) {
        return document.getElementById( el );
    }
    function total( un, qnt ) {
        return parseFloat(un.replace(',', '.'), 10) * parseFloat(qnt.replace(',', '.'), 10);
    }
    window.onload = function() {
        id('valorp').addEventListener('keyup', function() {
            var result = total( this.value , id('quantidade').value );
            id('valortotal').value = String(result.toFixed(2)).formatMoney();
        });

        id('quantidade').addEventListener('keyup', function(){
            var result = total( id('valorp').value , this.value );
            id('valortotal').value = String(result.toFixed(2)).formatMoney();
        });
    }

    String.prototype.formatMoney = function() {
        var v = this;

        if(v.indexOf('.') === -1) {
            v = v.replace(/([\d]+)/, "$1,00");
        }

        v = v.replace(/([\d]+)\.([\d]{1})$/, "$1,$20");
        v = v.replace(/([\d]+)\.([\d]{2})$/, "$1,$2");
        v = v.replace(/([\d]+)([\d]{3}),([\d]{2})$/, "$1.$2,$3");

        return v;
    };
</script>

Browser other questions tagged

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