Calculation of cubage with jquery

Asked

Viewed 558 times

1

Need to calculate width * height * length * quantity.

The Script is calculating only from fields that initial, those that are added according to need are not included in the calculation.

The first calculation is for each line:

#cubagemMateriais = (.comprimentoMaterial * .larguraMaterial * .alturaMaterial) * .volumeMaterial

Sum all #cubagemMaterials and displays on:

#cubagemMateriaisTotal

Testing

It seems the cloc doesn’t work.

My code:

<div id="formularioMateriais">
    <div class="row">
            Volume.........: <input name="volumeMaterial[]" id="" type="number" class="form-control volumeMaterial" value="" required><br>
            Material.........:<input name="nomeMaterial[]"  id="" type="text" class="form-control nomeMaterial" value="" required><br>
            Compimento..:<input name="comprimentoMaterial[]"  id="" type="text" class="form-control comprimentoMaterial" value="" required><br>
            Largura..........:<input name="larguraMaterial[]" id="" type="text" class="form-control larguraMaterial" value="" required><br>
            Altura.............:<input name="alturaMaterial[]"  id="" type="text" class="form-control alturaMaterial" value="" required>

            <a href="#" class="btn btn-success btn-xs adicionarCampo2" data-id="2" id="" style="margin:35px 0 0 0"><i class="fa fa-plus bigger-110 icon-only"></i>+ </a><br>

            <b>Soma da linha</b>.:<input name="cubagemMateriais[]" id="cubagemMateriais" type="text" >
            <hr>
    </div>
</div>
Soma total <input  id="cubagemMateriaisTotal" >

JS

$(function () {
    var divContent2 = $('#formularioMateriais');
    var botaoAdicionar2 = $('a[data-id="2"]');
    var i2 = 1;

    //Ao clicar em adicionar ele cria uma linha com novos campos
    $(botaoAdicionar2).click(function () {
        $('<div class="conteudoIndividual2"><div class="row"><div class="col-xs-1"><div class="form-group" style="margin:0 0 0 1px;"><label class="control-label">Volume</label><input name="volumeMaterial[]" type="number" class="form-control volumeMaterial" id="" value="" required></div></div><div class="col-xs-4"><div class="form-group" style="margin:0 0 0 1px;"><label class="control-label">Material</label><input name="nomeMaterial[]" type="text" class="form-control nomeMaterial" id="" value="" required></div></div><div class="col-xs-2"><div class="form-group" style="margin:0 0 0 1px;"><label class="control-label">Compimento</label><input name="comprimentoMaterial[]" type="text" class="form-control comprimentoMaterial" id="" value="" required></div></div><div class="col-xs-2"><div class="form-group" style="margin:0 0 0 1px;"><label class="control-label">Largura</label><input name="larguraMaterial[]" type="text" class="form-control larguraMaterial" id="" value="" required></div></div><div class="col-xs-2"><div class="form-group" style="margin:0 0 0 1px;"><label class="control-label">Altura</label><input name="alturaMaterial[]" type="text" class="form-control alturaMaterial" value="" required></div></div><div class="col-xs-1"><div class="form-group"><button class="btn btn-danger btn-xs linkRemover2" style="margin:35px 0 0 0"><i class="fa fa-times bigger-110 icon-only"></i></button></div><input name="cubagemMateriais[]" id="cubagemMateriais" ></div></div></div>').appendTo(divContent2);
        $('#removehidden2').remove();
        i2++;
        $('<input type="hidden" name="quantidadeCampos2" value="' + i2 + '" id="removehidden2">').appendTo(divContent2);
    });

    //Cliquando em remover a linha é eliminada
    $('#formularioMateriais').on('click', '.linkRemover2', function () {
        $(this).parents('.conteudoIndividual2').remove();
        i2--;
    });
});

/////////////////////////////////////////////////////////////////////////////////////////////////

$(document).ready(function () {
    $(".alturaMaterial, .comprimentoMaterial, .larguraMaterial, .volumeMaterial").on('keyup', function () {
        var $row = $(this).closest('.row');
        var cubagemMateriais = [".volumeMaterial", ".comprimentoMaterial", ".larguraMaterial", ".alturaMaterial"].reduce(function (soma, classe) {
            var value = parseInt($row.find(classe).val(), 10);
            return value * soma;
        }, 1);
        $row.find('input[name="cubagemMateriais[]"]').val(cubagemMateriais || 0);

        // somar todas as linhas
        var total = $('input[name="cubagemMateriais[]"]').get().reduce(function (soma, input) {
            var value = parseInt(input.value, 10);
            return value + soma;
        }, 0);
        $('#cubagemMateriaisTotal').val(total);
    });
});
  • Is there an HTML separator/wrapper for each line? Why mouseover?

  • This is a more simplified version. mouseover is only for testing.

  • The answer is much simpler if there is a line separator in HTML. Is there? like a div that contains each line?

  • @Sergio I separated the part of the form see on this link http://jsfiddle.net/y0x18e2p/ visually it looks like this http://i.imgur.com/Q8jrvdh.png

  • @Sergio Correction http://jsfiddle.net/y0x18e2p/1/

  • 1

    Please specify in the text of the question what the exact problem is.

  • @Marcusvinicius I think it’s the clone’s problem. I duplicated manually and it works, see http://jsfiddle.net/xp3v2grg/4, but when I use clone form it does not work http://jsfiddle.net/xp3v2grg/3/

  • How to resolve this issue of suspension?

Show 3 more comments

1 answer

1


It’s important to find a way to do this that is scalable. That is, have the same code regardless of the number of lines. This implies relying less on ID’s that are by nature unique. Suggested code:

$(document).ready(function () {
    $('#formularioMateriais').on('keyup', 'input', function (e) {
        var $row = $(e.target).closest('.row');
        var cubagemMateriais = [".volumeMaterial", ".comprimentoMaterial", ".larguraMaterial", ".alturaMaterial"].reduce(function (soma, classe) {
            var value = parseInt($row.find(classe).val(), 10);
            return value * soma;
        }, 1);
        $row.find('input[name="cubagemMateriais[]"]').val(cubagemMateriais || 0);

        // somar todas as linhas
        var total = $('input[name="cubagemMateriais[]"]').get().reduce(function (soma, input) {
            var value = parseInt(input.value, 10) || 0;
            return value + soma;
        }, 0);
        $('#cubagemMateriaisTotal').val(total);
    });
});

jsFiddle: http://jsfiddle.net/xp3v2grg/6/

The .reduce() is very useful here to add values from an array.

  • Here it is not calculating, it is always 0

  • @Tiago notices that I’m using classes. So I had to add class volumeMaterial in the first input, and also changed ID to class in the total input of each line.

  • it is calculated only one line, see http://i.imgur.com/uXSRjGT.png

  • I put the two codes together. The add new line and your calculation. In my file the add new line works, but this link does not, but gives to see how it is. see http://jsfiddle.net/xp3v2grg/1/

  • Updated http://jsfiddle.net/xp3v2grg/3/

  • I think the clone is the problem. I duplicated manually and it works, see http://jsfiddle.net/xp3v2grg/4/

  • @James: this works: http://jsfiddle.net/xp3v2grg/6/, using delegation as suggestion in response.

  • good morning. Your code worked, but it has a detail. Ex, I add lines the sum is right! But when I delete some line does not recalculate.

  • @Tiago http://jsfiddle.net/xp3v2grg/7/

  • It worked :), but I found another fault...rsrs, as the values placed there are in meters to find the cubic weight, does not appear the right result. Ex: 1.50 x 1.50 x 1.50 = 3.375 result is showing 1

  • @James uses parseFloat instead of parseInt -> http://jsfiddle.net/xp3v2grg/8/

  • It worked perfectly! what I’m going to ask is just a detail. Using the example Ex: 1.50 x 1.50 x 1.50 = 3.375 appears the correct value of three digits after the point in weight. But if I double for example, the result is 6.75 when zero at the end does not appear. It is to make it appear?

  • I forgot a detail. In the calculation of the ((Width * Height * Length) * Quantity) needs to be multiplied by 300, so. (((Width * Height * Length) * Quantity) * 300). Where I add the 300 to be multiplied?

  • @James on line 29 of this fiddle changes 1 for 300: http://jsfiddle.net/xp3v2grg/8/

  • 1

    Thank you very much again.

Show 11 more comments

Browser other questions tagged

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