0

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!

Peresoso
  • 5
  • 3

1 Answers1

0

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">

this is referencing to a node (HTML DOM Elements) and range to your specified input.

Also as @Taplar mentioned console.log() has to be inside the function.

More information about nodes can be found here: Difference between Node object and Element object?

Francisco
  • 228
  • 1
  • 7
  • The catch of the `this` in the arrow function is valid, but the console log is still in the wrong place. – Taplar Jan 22 '21 at 00:01
  • i got error using `this` on arrow function, that's why i pointed out. – Francisco Jan 22 '21 at 00:10
  • Francisco and @Taplar - Thank you, very much! Both 'this.value' and 'range.value' work fine for me. The problem was with the incorrect console.log() call. I should have called it in the function, where this variable is actually being used. Also, as I don't have any loop, the same function should have been called out right after 'if' statement in the EventListener. – Peresoso Jan 22 '21 at 01:29