2

Bom galera eu estou com o seguinte problema , eu tenho um painel simples de venda que mostra os produtos,quantidade,valor e valor total , assim que eu escolho um produto aparece o valor do item , o problema seria no caso como eu faria para que quando eu alterar a quantidade o valor total aumente conforme o tanto na quantidade

inserir a descrição da imagem aqui

se em quantidade eu colocasse 2 no valor total seria o dobro do valor 4,259,53 e cada vez somando mais 1 , alguém pode me da uma luz ?

Meu codigo :

<!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>
3
  • Veja se isso te ajuda. 4/01/2016 às 19:15
  • Seria bom por um trecho do código atual, fica mais fácil das pessoas ajudarem.
    – Largato
    4/01/2016 às 20:38
  • Opa, atualizei e postei o meu código espero que fique mais fácil para me ajudar 5/01/2016 às 11:20

3 Respostas 3

3

Use o 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>

Seria mais ou menos assim e você resolveria seu problema.

2
  • Alisson, corriji o código, pois havia erro nos parênteses. 5/01/2016 às 11:17
  • @IvanFerrer Obrigado! 5/01/2016 às 14:29
3

Uma solução bem grosseira más acho que é por ai.

Segue o código:

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
  • 2
    Oi Eric. Sua solução aparentemente resolve o problema do autor, porém é importante que você ponha a parte relevante do código na resposta, para que esta não dependa exclusivamente do link. (e pode manter o link para a pessoa testar, claro). Só pra constar, você inclusive pode por JS executável no Stack Overflow em Português, que dá pra testar aqui mesmo.
    – Largato
    4/01/2016 às 20:34
  • Ok. Vou editar a resposta.
    – Eric Silva
    5/01/2016 às 10:09
0

Bom galera depois de tanto tentar consegui resolver, obrigado a todos pela ajuda.

Consegui com esse código :

<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>

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .