Shree Dhushandhan
Shree Dhushandhan

Reputation: 11

How to get the input Range value and pass it to the value outside scope?

Here's my Question

HTML

<input type="range" onchange="price(this.value)">

JS

let priceRange = 0;

function price(value) {
    console.log(value);
    priceRange = value;
}

console.log(value);

Here I can access the input Range value inside the scope and store it in priceRange and log it, but not outside the scope, is there any solution for accessing the variable priceRange with the value of the input range value?

Any solutions would be appreciated!

Upvotes: 0

Views: 277

Answers (1)

vanowm
vanowm

Reputation: 10201

Just think about it. You have a function that's being executed when something happened, so how do you want be able access the result of that function before that "something" has happened? - you can't.

The only solution is either pass the result into global variable as you have priceRange and monitor it's change or use a callback function:

let priceRange = 0;

function price(value) {
//        console.log(value);
    priceRange = value;
    myCallback(value);
}

function myCallback(value)
{
  console.log("myCallback value", value);
  console.log("myCallback priceRange", priceRange);
}

//create an infinite loop to monitor changes in priceRange variable
let priceRangePrev = 0;
!function loop()
{
  if (priceRangePrev !== priceRange)
  {
    console.log("priceRange changed from", priceRangePrev, "to", priceRange);
    priceRangePrev = priceRange;
  }
  setTimeout(loop);
}()
<input type="range" onchange="price(this.value)">

Upvotes: 1

Related Questions