JohnMichael JohnMichael - 6 months ago 14
Javascript Question

How to pass value of an input range to a variable in JS?

How do you get the value of an input range slider into a variable? Below is the range I'm using. Suppose I drag the range to 12, then I need "12" as the variable that I want to then pass to a function.

<input type="range" min="1" max="30" value="15" />


Edit: I don't want a button to confirm the value or something, I want that everytime the value is changed, it gets passed to the function, so it'll be dynamic!

PS: It may not be the best question out there, but I've honestly tried looking for an answer before posting the question.

Answer

If you give an id to your field:

 <input id="myRange" type="range" min="1" max="30" value="15" />

then:

 $('#myRange').val();

First step it is not really required, but it makes things easier.

You can do this in every form field element:

 $('selector').val();

And you will get its value.

UPDATE FOR YOUR QUESTION:

Use .change event to bind a function that make whatever you want to do with this value, for example:

$('#myRange').change(function(){
    var myVar = $(this).val();
    alert(myVar);
});
Comments