Calculation of additional in percentage with jQuery

Asked

Viewed 62 times

-3

I am mounting an additional calculator for a product, but the additional ones are calculated in percentage. For example:

If the product is R$ 50,00 and is marked the checkbox that adds 40%, should change the price div to R$ 70,00.

If the first two are marked checkbox (40% and 15%), the expected value is R$ 127,50. The percentage should be based on the original price (in the case of two or more additional marked).

<input class="form-check-input" type="checkbox" value="40" id="adicional1">
  <label class="form-check-label" for="defaultCheck1">
    Adicional 1 - <strong>+40%</strong>
  </label>

<input class="form-check-input" type="checkbox" value="15" id="adicional2">
  <label class="form-check-label" for="defaultCheck1">
    Adicional 2 - <strong>+15%</strong>
  </label>

<input class="form-check-input" type="checkbox" value="30" id="adicional3">
  <label class="form-check-label" for="defaultCheck1">
    Adicional 3 - <strong>+30%</strong>
  </label>

<div id="price">R$ 50,00</div>

The code I tried to adapt and it didn’t work because it summing up the values and not the percentage.

$(document).ready(function(){
    $('.form-check-input').click(function (){
        var total = 0;
        $('.form-check-input:ckecked').each(function(){
            total += parseInt($(this).val());
            var formatado = total.toLocaleString("pt-BR", { style: "currency" , currency:"BRL"});
        });
        $('#price').html(formatado);
    });
});

How to transform this code so that some percentage?

  • First of all, do not use greetings or greetings, see what kind of behavior is expected from users? and how to create a [Mre] to prepare a question GOOD and CLEAR

  • to make these "additional" it is necessary to make the percentage calculation first (to get the correct result, if it will not just add up the values) the interpreter does not understand that % refers to percentage, so the calculation valor * (porcentagem / 100) that in this case 50 * (40 / 100) = 20

1 answer

0


From what I understand of your question..

is that you want to calculate values with additional (by visa discounts and promotions). Your code is only adding up the values and not the percentages, the interpreter does not understand that % refers to the percentage (not in this case). Your question you do not describe your need or where you want to get, so I suggest you DON’T LET to see How to create a Minimum, Complete and Verifiable example and How to ask a good question?


So I did all part of with the appropriate functionalities, from calculating the percentage to adding and printing on the page!

it is worth taking a look at the documentation MDN Web Docs: Basic Mathematics in Javascript for you to understand a little how the operators work and everything else..

var valor = conversor(document.querySelector('#price').innerHTML); // obtem o valor impresso
var valor_inicial = conversor(document.querySelector('#price').getAttribute('valor-inicial')); // obtem o valor inicial armazenado (nao sofre alterações)

// vai percorrer todos os inputs do tipo checkbox (referentes aos adicionais)
document.querySelectorAll('input[type=checkbox]').forEach(input => {
    input.addEventListener('click', function(e) {
        if (input.checked) { // ao ser marcado
            var porcentagem = valor_inicial * (conversor(input.value) / 100); // vai calcular a porcentagem sobre o valor inicial
            valor = valor + porcentagem; // soma o valor com a porcentagem calculada
            document.querySelector('#price').innerHTML = formatCurrency.format(valor); // imprime o resultado na div
        } else { // ao ser desmarcado
            var porcentagem = valor_inicial * (conversor(input.value) / 100); // vai calcular a porcentagem sobre o valor inicial
            valor = valor - porcentagem; // subtrai o valor da porcentagem calculada (resultado no valor anterior)
            document.querySelector('#price').innerHTML = formatCurrency.format(valor); // imprime o resultado na div
        }
    });
})

// vai tratar os valores para que não ocorra erros nos calculos (ex: NaN, undefined)
function conversor(input) {
    if (typeof input == 'number')
        return input;
    
    let res;
    input = input.toString().replace(/[^0-9,.]/g, '');
    if (input.match(/(,)\d{2}$/)) {
        res = input.replace(/\./g, '').replace(',', '.')
    } else {
        res = input.replace(',', '');
    }

    return parseFloat(res);
}


// formata o resultado final para ser impresso em moeda real
const formatCurrency = new Intl.NumberFormat('pt-BR', {
    style: 'currency',
    currency: 'BRL'
});
<input class="form-check-input" type="checkbox" value="40" id="adicional1">
<label class="form-check-label" for="defaultCheck1">
  Adicional 1 - <strong>+40%</strong>
</label>

<input class="form-check-input" type="checkbox" value="15">
<label class="form-check-label" for="defaultCheck1">
  Adicional 2 - <strong>+15%</strong>
</label>

<input class="form-check-input" type="checkbox" value="30">
<label class="form-check-label" for="defaultCheck1">
  Adicional 3 - <strong>+30%</strong>
</label>

  <br />
  
<div id="price" valor-inicial="50,00">R$ 50,00</div>

I preserved your code HTML not to run too far from its context!


Note! added some details..

The function conversor() to handle any unformatted text or number entries. When unchecking checkboxs the value is returned to the previous (without the independent add-on of how many are marked, if all are unchecked the value will remain the same as originally).

And added the function getAttribute() which will return the value of the element-specific argument, i.e. initial value because there would be no other way to get the real value of the "product" after making the changes.

  • It’s almost that. In the code example that was sent, when unchecked the additional, the value does not return to what it was before the calculation. Thanks for the lesson, from now on.

  • @Deyvidhenriquepereira you want that in addition to incrementing the additional ones, remove them if you uncheck the checkboxs?

  • Yes, the user may not want to add that additional to the product. So the calculation needs to be flexible.

  • just take the valor = valor - porcentagem and subtract that you will be removing the percentage of the value. Note! find a way to always store the values each time you add them, so you can "know" the value before adding the percentage.

  • If you helped in any way, if possible mark the answer as accepted and functional! is below the votes, so you can help others..

  • That’s right, when the value has decimals, the result is not as expected.

Show 1 more comment

Browser other questions tagged

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