Doubt to add values with for in Javascript

Asked

Viewed 142 times

1

Guys, I have the following PHP/HTML page:

<?php
include_once("conexao.php");
?>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> 
    <meta name="viewport" content="width=device-width, initial-scale=1.0"> 
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <script type="text/javascript" src="js/jquery-3.3.1.js"></script>
    <style type="text/css">

    body{
        background-color: #34495e;
    }
    p {
        color: white;
    }
    h3 {
        color: white;
    }
</style>
<script type="text/javascript">
        var x = 0; //initlal text box count
        function alerta(produto){
            var xmlhttp = new XMLHttpRequest();
            xmlhttp.onreadystatechange = function() {
                if (this.readyState == 4 && this.status == 200) {
                    document.getElementById("txtProduto"+x).innerHTML = "<input type='number' id='preco"+x+"' value='"+this.responseText+"'>";
                    //document.getElementById("tipo").focus();
                }
            }
            xmlhttp.open("GET", "pesquisa_preco.php?produto="+produto, true);
            xmlhttp.send();
        }

        $(document).ready(function() {
    var max_fields      = 20; //maximum input boxes allowed
    var wrapper         = $(".input_fields_wrap"); //Fields wrapper
    var add_button      = $(".add_field_button"); //Add button ID


    $(add_button).click(function(e){ //on add input button click
        e.preventDefault();
        if(x < max_fields){ //max input box allowed
            x++; //text box increment
            $(wrapper).append('<p>Produto '+x+'<select class="form-control" id="produto'+x+'" name="produto'+x+'" onchange="alerta(this.value)"></select><span id="txtProduto'+x+'"></span></p>');
            var xmlhttp = new XMLHttpRequest();
            xmlhttp.onreadystatechange = function() {
                if (this.readyState == 4 && this.status == 200) {
                    document.getElementById("produto"+x).innerHTML = this.responseText;
                        //document.getElementById("tipo").focus();
                    }
                }
                xmlhttp.open("GET", "pesquisa_produto.php?ativo=1", true);
                xmlhttp.send();
                window.scrollBy(0, 300);

            }
        });

    $(wrapper).on("click",".remove_field", function(e){ //user click on remove text
        e.preventDefault(); $(this).parent('div').remove(); x--;

    })
});

        function somaTotais(){
            for (var i = 1; i < x+1; i++) {
                var valor = parseFloat(document.getElementById("preco"+i+"").value, 10);
                window.alert(valor);
            }

        }

    </script>
    <title>Realizar Venda</title>
</head>
<body>
    <br><br><br><br>
    <div class="container">
        <button onclick="somaTotais(this)">Somar Totais</button>
        <form method="post" action="cadastra_venda.php" class="form-outline">
            <div class="row">
                <div class="col-md-2">
                    <p>Telefone: <input type="text" name="telefone" class="form-control"></p>
                </div>
                <div class="col-md-3">
                    <p>Cliente: <input type="text" name="cliente" class="form-control"></p>
                </div>
                <div class="col-md-3">
                    <p>Endereço: <input type="text" name="endereco" class="form-control"></p>
                </div>
            </div>
            <div class="row">
                <div class="col-md-3">
                    <div class="input_fields_wrap"></div><span id="txtProduto"></span>
                </div>
            </div>
            <p><button class="add_field_button btn btn-info">Adicionar novo produto</button></p>
            <div class="row">
                <div class="col-md-4">
                </div>
                <div class="col-md-4">
                </div>
                <div class="col-md-4">
                    <p>Valor Total: <input type="number" name="valor" class="form-control"></p>
                </div>
            </div>
            <p><input type="submit" name="submit" value="Realizar Venda" class="btn btn-success"></p>   

        </form>


    </div>



</body>
</html>
<?php
include_once("menu.php");
?>

I wanted help on this part:

 function somaTotais(){
            for (var i = 1; i < x+1; i++) {
                var valor = parseFloat(document.getElementById("preco"+i+"").value, 10);
                window.alert(valor);
            }

        }

Where it takes input values that are in the form, which are added dynamically, as in the print below:

inserir a descrição da imagem aqui

I wanted him to add his values to one variable, and throw me that variable later.

The way it is now, it gives me a window.Alert for every price, I wanted a window.Lert just with the sum of prices, but it seems I’m traveling and I can’t do it kkk

  • puts the window.alert outside the for, simple like :) for (var i = 1; i < x+1; i++) { .... aqui faz a soma ... }&#xA;window.alert(valor)

1 answer

1


The declaration of the variable value should not be inside fo loopr, you must use operator += to which result of each operation

parseFloat(Document.getElementById("preco"+i+""). value, 10);

Is accumulated in the variable value.

function somaTotais(){
   var valor = 0;
   for (var i = 1; i < x+1; i++) {
     valor += parseFloat(document.getElementById("preco"+i+"").value, 10);          
   }
   window.alert(valor);     
}
  • Do not answer only with code without any explanation. For all intents and purposes, the author of the question may not even be able to figure out what you changed in the code. Help whoever asked to realize what you did wrong so that you don’t do it in the future.

  • @Isac The harm of just including the code is that I was just writing the explanations in my reply but I didn’t have time to finish, so I dismissed why the code I was going to put is the same as the one proposed here.

  • Show, I did it! Gave me a blank of the use of FOR, so I was not getting, nor with angry prayer... Thanks!

Browser other questions tagged

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