Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
136 views
in Technique[技术] by (71.8m points)

Can't assign a value from Input element type 'range' to a variable in JavaScript

everyone.

I'm trying to get the value from an Input element type 'range' and assign it to the variable, but I keep getting 'undefined' type. Could you, please, advise, why does it happen and how can I assign type 'range' value to a variable?

let n;

let range = document.getElementById('range');
range.min = '0';
range.max = '100';
range.step = '1';
range.value = '20';

range.addEventListener('input', () => {
  if (this.value > 0 && this.value < 100) {
    n = this.value;  
  }
});

console.log(n);
'undefined'

Many thanks in advance!

question from:https://stackoverflow.com/questions/65837426/cant-assign-a-value-from-input-element-type-range-to-a-variable-in-javascript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Change input to see the value beeing printed in the console.

replace this with range.

let n;

let range = document.getElementById('range');
range.min = '0';
range.max = '100';
range.step = '1';
range.value = '20';

range.addEventListener('input', () => {
  if (range.value > 0 && range.value < 100) {
    n = range.value;  
  }
  console.log(n);
});
<input id="range" type="range">

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...