Product registration - create features

Asked

Viewed 767 times

-3

I am having great difficulty implementing dynamic results in my application ....

1 - When deleting a row, sort the rows correctly
2 - Calculate GENERAL shopping-cart total
3 - Recalculate the GRAND TOTAL by excluding a line
4 - CLEAR ALL FIELDS AND ZERO GENERAL TOTAL

So far I’ve only been able to add lines with fields and delete.

$(document).ready(function () {

    var contador = 0 ;

    //adiciona nova linha

    $("#addLinha").on("click", function () { 

        contador++;
        
        var newRow = $("<tr>");
        var cols = "";
        cols += '<td>' + contador + '</td>';
        cols += '<td><input class="produto" type="text" name="produto' + contador + '"/></td>';
        cols += '<td><input class="qtd" type="text" name="qtd' + contador + '"/></td>';
        cols += '<td><label text-align="center"><input align="center" class="preco" type="text" name="preco' + contador + '"/></label></td>';
        cols += '<td class="col-md-2 total">R$ 0,00</td>';
        cols += '<td><a class="deleteLinha"> Excluir </a></td>';
        newRow.append(cols);
        
        $("#products-table").append(newRow);
    });
    
    //chamada da função para calcular o total de cada linha
    $("#products-table").on("blur keyup", 'input[name^="preco"], input[name^="qtd"]', function (event) {
        calculateRow($(this).closest("tr"));
    });
    
    //remove linha
    $("#products-table").on("click", "a.deleteLinha", function (event) {
        $(this).closest("tr").remove();
    });

    // ******************************************************************************************************** //

    // Atalho para adicionar linha por tecla

    $(document).keypress(function(e){

    if(e.wich == 13 || e.keyCode == 13){ 
      //alert('A tecla ENTER foi pressionada');

      contador++;
        
        var newRow = $("<tr>");
        var cols = "";
        cols += '<td>' + contador + '</td>';
        cols += '<td><input class="produto" type="text" name="produto' + contador + '"/></td>';
        cols += '<td><input class="qtd" type="text" name="qtd' + contador + '"/></td>';
        cols += '<td><label text-align="center"><input align="center" class="preco" type="text" name="preco' + contador + '"/></label></td>';
        cols += '<td class="col-md-2 total">R$ 0,00</td>';
        cols += '<td><a class="deleteLinha"> Excluir </a></td>';
        newRow.append(cols);
        
        $("#products-table").append(newRow);

    }

    });

}); // FIM JQUERY



//função para calcular o total de cada linha 
function calculateRow(row) {

    var preco = +row.find('input[name^="preco"]').val();
    var qtd   = +row.find('input[name^="qtd"]').val();

    //2 casas decimais
    var total = (preco * qtd).toFixed(2);

    //substitui ponto por virgula
    total = total.replace(".", ",");

    //a regex abaixo coloca um ponto a esquerda de cada grupo de 3 digitos desde que não seja no inicio do numero
    row.find('.total').html("R$ " + (total).replace(/\B(?=(\d{3})+(?!\d))/g, "."));     
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<table id="products-table" class="table table-striped table-bordered table-hover">

    <thead>
      <tr>

        <th class="cabecalho">Nº</th>
        <th class="cabecalho">Produto</th>
        <th class="cabecalho">Quantidade</th>
        <th class="cabecalho">Valor Unitário</th>
        <th class="cabecalho">Valor Total</th>
        <th class="cabecalho"></th>

      </tr>
    </thead>
    
    <tbody class="row">    </tbody>
    
    <tfoot>

    <tr>

      <td colspan="4" style="text-align: left;">
        <button class="btn btn-info waves-effect w-md waves-light m-b-5"  id="addLinha" type="button">Adicionar Produto</button>
      </td>

      <td>
        <label><b>TOTAL GERAL</b></label>
      </td>

      <td>
        
      </td>

    </tr>

  </tfoot>

</table>

  • 3

    The four points indicated in the question are what you are asking for help in concluding ? If so, it certainly seems to me to be too broad. If that’s not the case, indicate which one you’re trying to do

  • It is a personal project that I developed and am implementing, but I have no advanced knowledge in Jquery and work with dynamic inputs .... if you can help me I appreciate.

2 answers

2


I made a simple code to start but you must improve for your application

Reorder:

function reordenar() {
    var num = document.getElementsByClassName('contador')

    for(var i = 0; i < num.length; i++) {
        num[i].firstChild.nodeValue = i
    }
}

Note - you need to add class to your code:

cols += '<td class="contador">' + contador + '</td>';

Grand total:

function total() {
    var parcial = document.getElementsByClassName('total')
    var total = 0

    for(var i = 0; i < parcial.length; i++) {
        var parc
        parc = parcial[i].firstChild.nodeValue.replace("R$ ", "")
        parc = parc.replace(".", "") //IMPORTANTE - Tirar os pontos (a cada 3 dígitos, exemplo, 1.355.000,00) antes de trocar "," por "."
        parc = parc.replace(",", ".")

        total += parseInt(parc)
    }

    console.log(total)
}

To recalculate the overall total just call the function when the user deletes

I don’t quite understand what you mean by deleting everything but if you want to reset the table you can use this:

document.getElementsByTagName('tbody')[0].innerHTML=''

then just call the calculate total function to recalculate and it will be zero. or simply reload the page

  • Very good friend, I took your idea and managed to walk a little ... agr I’m having difficulty to calculate the total when the value of above 1.000,00 ... da um help ae, see how this getting.

  • I edited the answer with the correction, the problem was the point every 3 digits of the number, if you have no more doubts do not forget to close the question (with me if possible hsauhusahasu)

  • It’s not working yet..... and I’ll need the last two decimal places !!

  • Sorry my mistake is not replace(".", ",") and yes replace(".", ""), also don’t forget to do this BEFORE changing the comma by the dot

  • TOP heimmm , I tried every possible way and did not reach the result rsrsrs .... agr in your opinion, which best format to save in mysql ??? I imagine would be DECIMAL (10.2) what do you think ...

  • Take a look in that question that has to do with it, if my answer there is not enough make a comment there or open a new question

  • very useful, really for finances the DECIMAL is the recommended !! #Grateful

Show 2 more comments

1

see the table ordering the lines and calculating the total value:

$(document).ready(function () {

    var contador = 0 ;



    //adiciona nova linha

    $("#addLinha").on("click", function () { 

        contador++;
        //ordenar();
        
        var newRow = $("<tr>");
        var cols = "";

        cols += '<td class="contador" >' + contador + '</td>';
        cols += '<td><label text-align="center"><input class="produto" type="text" name="produto' + contador + '"/></label></td>';
        cols += '<td><label text-align="center"><input class="qtd" type="text" name="qtd' + contador + '"/></label></td>';
        cols += '<td><label text-align="center"><input align="center" class="preco" type="text" name="preco' + contador + '"/></label></td>';
        cols += '<td class="col-md-2 total">R$ 0,00</td>';
        cols += '<td><a class="deleteLinha"> Excluir </a></td>';

        newRow.append(cols);
        
        $("#products-table").append(newRow);
    });
    
    //remove linha
    $("#products-table").on("click", "a.deleteLinha", function (event) {

        $(this).closest("tr").remove();

        reordenar();

        //total();
    });

    //chamada da função para calcular o total de cada linha
    $("#products-table").on("blur keyup", 'input[name^="preco"], input[name^="qtd"]', function (event) {
        
        calculateRow($(this).closest("tr"));

        var z = valor_total(); console.log('teste - '+ z );

        //$("#valor_total").val(z) ; 

        $('#valor_total').html("R$ " + (z) );   
        //console.log( z );

    });


}); // FIM JQUERY


// Ordernar linhas

function ordenar() 
{

var num = document.getElementsByClassName('contador') ; //console.log(num.length);

    for(var i = 1; i < num.length ; i++) { 

        num[i].firstChild.nodeValue = i ; //console.log(i);

    }
}

// Reordernar linhas

function reordenar() 
{

var num = document.getElementsByClassName('contador') ;

    for(var i = 0 ; i < num.length ; i++) { 

        num[i].firstChild.nodeValue = i+1 ; //console.log(i);
    }
}

//função para calcular o total de cada linha 

function calculateRow(row) {

    var preco = +row.find('input[name^="preco"]').val();
    var qtd   = +row.find('input[name^="qtd"]').val();

    //2 casas decimais
    var total = (preco * qtd).toFixed(2);

    //substitui ponto por virgula
    total = total.replace(".", ",");

    //a regex abaixo coloca um ponto a esquerda de cada grupo de 3 digitos desde que não seja no inicio do numero
    row.find('.total').html("R$ " + (total).replace(/\B(?=(\d{3})+(?!\d))/g, "."));     

}

function valor_total() {

    var parcial = document.getElementsByClassName('total') ;

    var total = 0 ;

    var parc  = 0 ;

    for(var i = 0; i < parcial.length; i++) {

        parc = parcial[i].firstChild.nodeValue.replace("R$ ", "") ;

        total +=  parseFloat(parc) ; 

        console.log(parc);
    } 

    //substitui ponto por virgula
    //total = total.replace(".", ",");

    return total.toFixed(2) ; 

}

// Aceitar apenas numeros no input
  function somenteNumeros(num) {

        var er = /[^0-9.]/;

        er.lastIndex = 0;

        var campo = num;
        
        if (er.test(campo.value)) {
          campo.value = "";
        }

    }

</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<table id="products-table" class="table table-striped table-bordered table-hover">

    <thead>
      <tr>

        <th class="cabecalho">#</th>
        <th class="cabecalho">Produto</th>
        <th class="cabecalho">Quantidade</th>
        <th class="cabecalho">Valor Unitário</th>
        <th class="cabecalho">Valor Total</th>
        <th class="cabecalho"></th>

      </tr>
    </thead>
    
    <tbody class="row">    </tbody>
    
    <tfoot>

    <tr>

      <td colspan="4" style="text-align: left;">
        <button class="btn btn-info waves-effect w-md waves-light m-b-5"  id="addLinha" type="button">Adicionar Produto</button>
      </td>

      <td>

        <label id="valor_total"><b>
          <!--input type="text" name="valor_total" id="valor_total" value="" --></b></label>
      </td>

      <td>
        
      </td>

    </tr>

  </tfoot>

</table>

Browser other questions tagged

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