Home > Net >  Automatic change of input fields through Event Handler "onkeyup"
Automatic change of input fields through Event Handler "onkeyup"

Time:04-14

I am pretty bad at JS but I need some help at a task in order to prepare for a small exam on web technology.

The task:

I have to write a code where two input fields have to be displayed. The sum of both of the input fields have to be 100. So the input fields will be mainly used for typing in some numbers.

When I type a number in the first input field between 0 - 100 there should be displayed the remaining amount of 100 in the second input field after typing the last number of the first number. This should be also working vice versa. So it should be irrelevant which input field I type in the number. Our professor suggests us to use the event handler "onkeyup".

One example:

First Input field: 3 -> typed in

Second Input field: 97 -> will be shown automatically after typing 3

Please don't laugh, here is my code:

<!DOCTYPE html>
<meta charset="UTF-8">
<html>
    <head>
        <script>
            function calc() {
                var firstnum = document.getElementById("firstprop").value;
                var secondnum = document.getElementById("secondprop").value;
                var firstresult = 100 - parseInt(secondnum);
                var secondresult = 100 - parseInt(firstnum); 
                if(firstnum >=0){
                    secondnum = secondresult;
                }
                if(secondnum >=0){
                    firstnum = firstresult;
                }
            }
        </script>
    <head>
    <body>
        <input type="text" onkeyup="calc()" id="firstprop"/>
        <input type="text" onkeyup="calc()" id="secondprop"/>
    </body>
</html>

Thank you very much for your help. I appreciate it, really :)

CodePudding user response:

Here you are

<!DOCTYPE html>
<meta charset="UTF-8">
<html>

<head>
  <script>
    function calc(value, index) {
      if (index == 1) {
        document.getElementById("secondprop").value = 100 - value;
      } else if (index == 2) {
        document.getElementById("firstprop").value = 100 - value;
      }
    }
  </script>

  <head>

    <body>
      <input type="text" onkeyup="calc(this.value, 1)" id="firstprop" />
      <input type="text" onkeyup="calc(this.value, 2)" id="secondprop" />
    </body>

</html>

CodePudding user response:

function calc(e) {
            if (e.target.id === "firstprop") {
                var secondElement = document.getElementById("secondprop");
                var value1 = e.target.value ? e.target.value : 0;
                secondElement.value = 100 - (parseInt(value1));
            }

            if (e.target.id === "secondprop") {
                var secondElement = document.getElementById("firstprop");
                var value2 = e.target.value ? e.target.value : 0;
                secondElement.value = 100 - (parseInt(value2));
            }
        }
    </script>
  • Related