How to Make the following function in pure javascript?

Asked

Viewed 55 times

-1

I would like to make the following calculation: take the amount of value to pay,take the value of the days of delay and that when clicking the confirm button do the following calculation: value_a_pay*(delay*2)/100, I tried this but it did not work

html:

<div class="form-group">
  <label> Pagamento De Janeiro</label>
  <br>
  {% for s in students %}
  <span>Valor a pagar <strong id="pag_jan">{{s.fee}}</strong><div class="form-content"><form>
      <div class="input-group mb-3"> <label>Dias de atraso</label><input type="search" placeholder="" 
           name="atraso" id="atraso" value="0">
        <button class="btn btn-light" type="submit" onclick="calc()">confirmar</button></span>
  {%endfor%}
  {% render_field form.jan_pay class="form-control" %}
  
</div>

<script>
   var pag= document.getElementById("pag_jan")
   var result= pag.innerText
   var atraso = document.getElementById("atraso")
   var result_atraso = atraso.value

   function calc(e) {
      e.preventDefault();
        if(result_atraso <=0 ){
          return
     }else{
      var resultado =  result*(result_atraso*2)/100
      console.log(resultado)
    }
   }

     
</script>
  • 2

    but this code is already pure js

  • but it doesn’t work

  • 1

    then you need to debug and find out what happens, look at the console and see if there are errors

1 answer

0


The problem is you’re getting the value atraso.value out of function calc. Then this value is loaded only once, when the page loads, and is never updated.

If the idea is to take what has been filled, take the value within the function:

// os elementos podem ser pegos fora da função mesmo
var pag = document.getElementById("pag_jan");
var atraso = document.getElementById("atraso");

function calc(e) {
  e.preventDefault();
  // pegue os valores dentro da função
  var result = pag.innerText;
  var result_atraso = atraso.value;

  if (result_atraso <= 0) {
    return;
  } else {
    var resultado =  result * (result_atraso * 2) / 100;
    console.log(resultado);
  }
}

// associar o evento de clique à função calc
document.getElementById("botao").addEventListener('click', calc);
<label> Pagamento De Janeiro</label>
<br>
<span>Valor a pagar <strong id="pag_jan">100</strong>
  <form>
    <label>Dias de atraso</label>
    <input type="search" name="atraso" id="atraso" value="0">
    <button id="botao">confirmar</button>
  </form>
</span>

And in Javascript I also put a semicolon at the end of the lines. It may sound "fresh," and I know that Javascript "accepts" the semicolon code and "works," but it avoids some bizarre situations that can occur if you don’t use them, like that one and that one (see more about this here).

  • Thanks friend worked, I had heard about the stitches and commas but as I program a lot in python I end up forgetting

Browser other questions tagged

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