Value of HTML input range, getattribute vs value

2.5k views Asked by At

I have created HTML INPUT element with type="RANGE" and with id="slider". Why cannot I access its value using getAttribute("value") method? Debugger shows that there is an attribute named "value" with some value which is not equal to the value of the element. Should not the value of range element be its attribute?

var sliderValue1=document.getElementById("slider").getAttribute("value");
var sliderValue2= document.getElementById("slider").value;
2

There are 2 answers

0
Frogmouth On BEST ANSWER

Why cannot I access its value using getAttribute("value") method?

you can't do that because, .getAttribute("value") return the value of the element write into the html (if you don't change that, the default value).

Example:

with: <input type="range" id="slider" value="500">

document.getElementById("slider").getAttribute("value"); return 500 also if you use input to change range.

Debugger shows that there is an attribute named "value" with some value which is not equal to the value of the element.

It's true, and right. If you set a default value it never change (is useful to reset the input).

Should not the value of range element be its attribute?

No, the current value of the element is stored outside the html, so to access to the current vale you must use: document.getElementById("slider").value;, but it's the same with all type of input not only on range.

$(function(){
    $("input[name=foo]").on("change",function(){
        var val = $(this).val();
        var attr = $(this).attr("value");
        var prop = $(this).prop("value");
        console.log(" --- JQUERY TEST JS ----");
        console.log("Current value: (using .val)",val);
        console.log("Initial value: (using .attr)",attr);
        console.log("Current value: (using .prop)",prop);
    });
});

//NATIVE JS
function originalJS(){
    console.log(" --- ORIGINAL JS ----");
    console.log("Current value: (using .value)",this.value);
    console.log("Initial value: (using .attr)",this.getAttribute("value"));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<input type="range" onChange="originalJS.call(this)" name="foo" value="500"/>
<p>RUN AND WATCH CONSOLE :) ... watch value="500" (but range is 0-100)</p>

<input type="text" onChange="originalJS.call(this)" name="foo" value="500"/>

0
MarsOne On

There is very little documentation on Input Type=RANGE on the internet...

It is not supported in ie9 and older browsers since it is a newer HTML5 element.

Here is a Demo on how it works

Here is the code I used.

HTML

<p>Minimum =0, Maximum = 100, Step = 5</p>
<input id="slider" type="range" min="0" max="100" step="5" onchange="printValue('slider','rangeValue')">
<input id="rangeValue" type="text" size="5" />

JS

function printValue(sliderID,TextBoxID){    document.getElementById(TextBoxID).value=document.getElementById(sliderID).value;
}