Javascript - discount from x units

Asked

Viewed 52 times

3

I built this code, but I can’t get it to display the result with the full discount from 'x' units:

de : <span id="APrecoDe">46.50</span><br><br>
por : <span id="APrecoPor">43.50</span><br><br>
qnt : <input type="text" id="Aunidades" onblur="calcular();" value="1" /><br><br>
qmin: <span id="Amin">2</span><br><br>
Seu desconto total é de: R$<span id="resultado"></span>

<script>
  function calcular() {
      var num1 = Number(document.getElementById("APrecoDe").innerHTML);
      var num2 = Number(document.getElementById("APrecoPor").innerHTML);
      var num3 = Number(document.getElementById("Aunidades").value);
      var num4 = Number(document.getElementById("Amin").innerHTML);

      if (num3 >= nun4) {
        var dif = num1 - num2;
        if (elemResult.textContent === undefined) {
          elemResult.textContent = "O resultado é " + String(dif * num3) + ".";
        } else { // IE
          elemResult.innerText = "O resultado é " + String(dif * num3) + ".";
        }
        var elemResult = document.getElementById("resultado");

      }
</script>
  • 2

    There’s a key missing from that code, no?!

  • 1

    the variable num4 is with N no if

1 answer

3


Script missing a lock key, variable elemResult was declared after use and the element resultado had not been defined. The result would be the following:

function calcular() {
  var de = Number(document.getElementById("APrecoDe").innerHTML);
  var por = Number(document.getElementById("APrecoPor").innerHTML);
  var unid = Number(document.getElementById("Aunidades").value);
  var min = Number(document.getElementById("Amin").innerHTML);
  var elemResult = document.getElementById("resultado");

  if (unid >= min) {
    var dif = de - por;

    if (elemResult.textContent === undefined) {
      elemResult.textContent = "O resultado é " + String(dif * unid) + ".";
    } else { // IE
      elemResult.innerText = "O resultado é " + String(dif * unid) + ".";
    }
  }
}
<label>de  : </label><span id="APrecoDe">46.50</span><br><br>
<label>por : </label><span id="APrecoPor">43.50</span><br><br>
<label>qnt : </label><input type="text" id="Aunidades" onblur="calcular();" value="1" /><br><br>
<label>qmin: </label><span id="Amin">2</span><br><br>
<span id="resultado"></span><br><br>

Browser other questions tagged

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