5

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.

6 Answers 6

4

You just need to bind to the change event:

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

$("input").change(function(){
    var value = $(this).val();
    alert(value);
})
Sign up to request clarification or add additional context in comments.

Comments

2

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

1

Just use register an event on the input:

<input type="range" min="1" max="30" value="15" oninput="alert(this.value)" />

you could of course also call a function in the oninput field.

Comments

1

jsfiddle

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

var input = document.getElementById('field');
console.info(input.defaultValue); // value default (15)
input.onchange = function () {
  console.info(input.value); // value change
};

Comments

1

You can do this simply by adding a listener to the field's input event, updating your variable every time it fires.

var input=document.querySelector("input"),
    value=input.value;
console.log(value);
input.addEventListener("input",function(){
    value=this.value;
    console.log(value);
},0);
<input max="30" min="1" type="range" value="15">

Comments

0

Give the input an Id. Then use For JQuery

Var a = $('#whateverId').val();

For JavaScript

Var a = getElementById('whateverID).innerHtml;

1 Comment

this is "dynamic". variable will not be changed

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.