Subtraction in jquery

1

I have this function in javascript, and wanted to pass it to jquery. The user clicks a button in html 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>'
    
asked by anonymous 26.08.2017 / 23:45

2 answers

1

With jquery it 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><inputtype="checkbox" name="ssbc" id="ssbc" />
<input type="button" id="calculo" value="Calcular" />
  

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

     

The $("#calculo").on("click", function(){ line can be replaced with $('#calculo').click(function (){ , which will work fine as well.

To find out the difference between .on(“click”, function()) e o .click(function()) access this post

    
27.08.2017 / 02:04
0

This example is only 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:<inputid="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>
    
27.08.2017 / 02:58