Use Javascript condition for mathematical operations

Asked

Viewed 33 times

0

Hello! I am trying to perform a different calculation in JS so that according to the number of employees, the total value is changed.

The condition would be as follows: by inserting a value of 1 to 5 into the input, this value is multiplied by 50 and presented in the span in monetary value; Inserting a value of 6 to 10, the value is multiplied by 45 and the result is displayed in the span in monetary value;

And so on. The person needs to enter the value in the field to show the result in span but must follow the conditions.

I tried with if, If if but I did not succeed, I know it is something very simple so I ask for help from the university.

There is also the possibility of the result to appear on time without pressing button or TAB key?

My code is like this:

<form action="" method="post">
  Número de Funcionários: <input type="number" id="num1" onblur="calcular();" />
  <span id="resultado"></span>

  </form>

<script type="text/javascript">
if (num1 < 5) {

function calcular() {
var num1 = Number(document.getElementById("num1").value);
var func1 = 50;
var elemResult = document.getElementById("resultado");
elemResult.textContent = "O resultado é " + String(num1 * func1) + ".";
}

}

else if (condição ??) {

function calcular() {
var num1 = Number(document.getElementById("num1").value);
var func1 = 10;
var elemResult = document.getElementById("resultado");
elemResult.textContent = "O resultado é " + String(num1 * func1) + ".";
}

}

</script>
  • Arthur, format the code better buddy.

1 answer

0


Use If inside Function, not IF to condition which Function will be.

function calcular() {
    var num1 = Number(document.getElementById("num1").value);
    var elemResult = document.getElementById("resultado");
    var func1 = 0;


    if (num1 < 5) {
        func1 = 50
    } else if (num < 10) {
        func1 = 45
    }

    elemResult.textContent = "O resultado é " + String(num1 * func1) + "."
};

to use without pressing, only when typing, utileza o onKeyPress, onKeyDown

  • Perfect, I changed some conditions of the code and it worked correctly. Thank you very much!

Browser other questions tagged

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