Subtraction in jquery

Asked

Viewed 548 times

1

I have this function in javascript, and I wanted to pass it to jquery. The user clicks on an html button and calls the function for a discount.`

<script>  
function verifica(){ 
  var preco = 100; 
  var desconto = 0.30; 
  var total; 
  if(document.getElementById('ssbc').checked == true){ 
    total = preco -(preco*desconto);
  }
  if(document.getElementById('ssbc').checked == false){
    total=preco;
  }
  alert("O valor de sua inscrição é: R$ "+total);
}
</script>`
  • Welcome, don’t forget to read this post https://pt.meta.stackoverflow.com/questions/1078/como-e-por-que-aceitar-uma-resposta/1079#1079

2 answers

1

With jquery can be done as follows:

$(document).ready(function () {
   var preco = 100; 
   var desconto = 0.30; 
   var total;

    $("#calculo").on("click", function(){
        if(ssbc.checked) {
            total = preco -(preco*desconto);
        } else {
            total = preco;
        }
        //alert("O valor de sua inscrição é: R$ "+total+",00");
        console.log("O valor de sua inscrição é: R$ "+total+",00");
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="checkbox" name="ssbc" id="ssbc" />
<input type="button" id="calculo" value="Calcular" />

$(document).ready means that we will execute the function once the html elements are placed on the page.

The line $("#calculo").on("click", function(){ may be replaced by $('#calculo').click(function (){ which, in that case, will also work to the satisfaction of.

To know the difference between .on(“click”, function()) e o .click(function()) access that post

  • The reply from @Leocaracciolo is absolutely correct.

0

This example is just an alternative where values can be entered by the user.

$('#aplicar').click(function(){
    $('#desconto').slideToggle();
  });

$('#calcular').click(function(){
    if ($("#aplicar:checked").length) {
      $('#total').text("O valor de sua inscrição é: R$ " + parseFloat($('#preco').val() - $('#valDesconto').val()).toFixed(2));
    } else {
      $('#total').text("O valor de sua inscrição é: R$ " + parseFloat($('#preco').val()).toFixed(2));
    }
})
#desconto { display: none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<form>
  Preço: <input id="preco" type="number" step="0.01"><br>
  <label for="aplicar">Aplicar desconto</label>
  <input type="checkbox" id="aplicar"><br>
  <div id="desconto">
    Desconto: <input id="valDesconto" type="number" step="0.01" placeholder="Desconto">
  </div>
  <input type="button" id="calcular" value="Calcular">
  <h1 id="total"></h1>
</form>

Browser other questions tagged

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