Brandon Brandon - 5 months ago 36
jQuery Question

Trying to get a sliderbar to alter a textfield value in HTML

I have a sliderbar that takes input from the textfield and resets its position accordingly; however, I cannot figure out how to do the following:


  1. Make it so that the sliderbar repositions itself for any value within the range, not just non-decimal inputs.

  2. Make it so that the textfield value changes accordingly as the sliderbar is toggled.



The code can be found below.

Any help is appreciated, thank you!

<div>
<input id="slider" type="range" min="0" max="2" step="0.001"/>
<input id="input" type="text" value="1"/>
</div>

<script>
var slider = document.getElementById('slider');
$('#input').change(function(){
slider.value=parseInt(this.value)
});
</script>

Answer

I have a sliderbar that takes input from the textfield and resets its position accordingly;

I don't see how that work with the code given since you're using parseInt and would need parseFloat for that. Anyway, below is what you asked for:

$('#input').change(function() {
  $('#slider').val(parseFloat(this.value))
});
$('#slider').on("input change", function() {
  $('#input').val(this.value)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div>
  <input id="slider" type="range" min="0" max="2" step="0.001" />
  <input id="input" type="text" value="1" />
</div>