How to get values from HTML5 Input Type Range using JavaScript

← PrevNext →

We often use the HTML5 Range input type element as a range selector on e-commerce sites. Here in this post, I am sharing few simple JavaScript example showing how to extract or read values from Input type Range and submit the values.

Read HTML5 Range Slider Value using JavaScript

I am not using any code behind procedure or an API for data submission; the example here focuses mainly on how to extract the values from the Range slider (the element), show the values in a <label> and update the browser URL with the values, using only JavaScript.

The example uses two different attributes namely, oninput (HTML5 element) and onchange, to call JavaScript methods to read or extract the values from Range slider.

The HTML5 Input Type Range

<input type= 'range' />

Browser Support:
Chrome 39.0 - Yes | FireFox 34.0 - Yes | Internet Explorer 10 - Yes | Safari - Yes

The Markup

Note: The Example does not validate the From and To Range sliders. It just reads the range values.

<div>
    <p>
        <label>Price From:</label>
        <input type="range" id="fromPrice" value="50" min="0" max="500" 
            oninput="document.getElementById('fPrice').innerHTML = this.value" />
        <label id="fPrice"></label>
    </p>
    <p>
        <label>Price To:</label>
        <input type="range" id="toPrice" value="450" min="0" max="500" 
            oninput="document.getElementById('tPrice').innerHTML = this.value" />
        <label id="tPrice"></label>
    </p>
    <p><input type="submit" value="submit" onclick="ti()" /></p>
</div>

In the above markup, I am using oninput attribute to update the labels with the Range values. Note: The JavaScript function ti() is at the end of this blog post.

Syntax of HTML5 "oninput" Event Attribute

oninput='someFunction()'

The oninput event attribute calls a JavaScript function when you input a value, in our case it’s the Range slider. The attribute immediately updates a label with range value when a user moves the slider.

Try it

Syntax of onchange Event Attribute

onchange='someFunction()'

The onchange event attribute is different from oninput event attribute. The onchange updates the label, once the user drags and stops the slider (at a particular location).

Try it

You may also like: What is HTML5 <aside> tag and How to use it in your Website

The Script

Here’s how you can read the values in the labels (that we updated using Range slider), using JavaScript after clicking the submit button. Once we have Range slider values, we can update the browser URL using window.location.replace() method.

<script>
    function ti() {
        var fP = document.getElementById('fPrice').innerHTML;
        var tP = document.getElementById('tPrice').innerHTML;

        if (fP != '' && tP != '')
            window.location.replace(window.location.href + '?min_Price=' + fP + '&max_Price=' + tP);
    }
</script>

Thanks for reading.

← PreviousNext →