Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Bind Array of numbers to Range Slider using JavaScript/Jquery/Knockout JS

I tried this below code:

<input type="range" id="slider1" min="0" max="6" step="1" value="1">
<output id="output"></output>
var values = [2, 4, 8, 16, 32, 64, 128];
$('#slider1').change(function () {
    $('.slider #slider1').attr('value', values[this.value]);
    memoryslider = $('input[id="slider1"]').attr('value');
    var data = document.getElementById("output");
    data.innerText = memoryslider;
});

This works fine but out put showing after mouse click, But i want to output values when mouse is moving, is there any possibility please help me..

like image 247
Devi Prasad Avatar asked Jul 19 '26 13:07

Devi Prasad


1 Answers

To achieve the update of the #output element while the range is being dragged you should use the input event. You also shouldn't change the value attribute manually on change of the input. Try this:

var values = [2, 4, 8, 16, 32, 64, 128];
$('#slider1').on('change input', function() {
  var value = values[this.value];
  $("#output").text(value);
}).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="range" id="slider1" min="0" max="6" step="1" value="1">
<output id="output"></output>

Also note that as all your values are powers of 2 you can use the Math.pow() method instead of hard-coding the values in to an array:

$('#slider1').on('change input', function() {
  var value = Math.pow(2, +this.value + 1);
  $("#output").text(value);
}).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="range" id="slider1" min="0" max="6" step="1" value="1">
<output id="output"></output>
like image 128
Rory McCrossan Avatar answered Jul 21 '26 04:07

Rory McCrossan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!