skip to Main Content

I’ve got a function like this (value is from select):

function getSelectValuePower () {
 var power = document.getElementById("power").value;
  sessionStorage.setItem("power", power);
  console.log(power);
}

How can I use value from variable power in another function ?
For example :

I want to use it here :

function getValue () {
  var number = 10;
  var selectedValue = number + power;
  console.log(selectedValue2);
}

So, when my power is 7, the result in getValue() should be 17.

I tried to do it with global variables, but doesn’t work.

3

Answers


  1. Get power in second function:

    var power = sessionStorage.getItem("power");
    
    Login or Signup to reply.
  2. you can also use parseInt() as well

    function getValue() {
      const number = 10;
      const power = parseInt(sessionStorage.getItem("power")) || 0;
      const selectedValue = number + power;
      console.log(selectedValue);
    }
    
    Login or Signup to reply.
  3. You can do it by declaring power outside the function or by creating a class. Here’s how you can do it.

    Using global declaration:

    var power = document.getElementById("power").value;
    function getSelectValuePower() {
        sessionStorage.setItem("power", power);
        console.log(power);
    }
    
    function getValue() {
        var number = 10;
        var selectedValue = number + power;
        console.log(selectedValue);
    }
    

    Using a class:

    class PowerSelector {
      constructor() {
        this.powerElement = document.getElementById("power");
        this.number = 10;
      }
    
      getSelectValuePower() {
        const power = this.powerElement.value;
        sessionStorage.setItem("power", power);
        console.log(power);
      }
    
      getValue() {
        const selectedValue = Number(this.number) + Number(this.powerElement.value);
        console.log(selectedValue);
      }
    }
    
    const powerSelector = new PowerSelector();
    powerSelector.getSelectValuePower();
    powerSelector.getValue();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search