How do I show the value of the input type range

7

Well, I have the following code:

<input type="range" name="vol" min="0" max="100">

I would like to know how I could do next to show the real time value that is selected, ie the user dragged with the "bar" in the range and next to the value that had selected.

Thank you first.

    
asked by anonymous 03.07.2016 / 03:13

2 answers

10

The event you need to use is input . Just wait for it to occur and then retrieve the value of the value attribute of your range :

var $range = document.querySelector('input'),
    $value = document.querySelector('span');

$range.addEventListener('input', function() {
  $value.textContent = this.value;
});
<input type='range' value='50' max='100'>
<span>50</span>
    
03.07.2016 / 04:17
10

@renan already posted a good solution (and already took my +1), I'll leave here a similar alternative, with a few differences in the syntax and methods used:

<input type="range" name="vol" value="0" min="0" max="100"
    oninput="display.value=value" onchange="display.value=value">
<input type="text" id="display" value="0" readonly>
  • The oninput property calls a JS function, and is usually "realtime", but is less compatible than using onchange (eg IE does not work).
  • onchange works in more browsers , but it is not in all that it updates in realtime, so we use both simultaneously.


Of curiosity, you can make it work in two ways. Editing the text field, the slider accompanies it. By moving the slider, the text field accompanies:

<input type="range" id="vol" name="vol" value="0" min="0" max="100"
    oninput="display.value=value" onchange="display.value=value">
<input type="text" id="display" value="0"
    oninput="vol.value=value" onchange="vol.value=value">
    
03.07.2016 / 06:36