Daniel Yantis Daniel Yantis - 2 months ago 12
Javascript Question

Understanding jQuery UI (basic): How to set the value of a slider

The real problem is that I just have not learned enough basic JavaScript yet. I'm learning but it's got me all messed up right now.

So I figure this is really simple but I can't put my head around it yet.

I had some code that I finally got working just great and I understood it well enough, then I got help (and it's works great too) but I don't understand the way you select an object and change it's value using jQuery.

Here is the new code (working great):

.html

<div style="display:block;margin:100px auto;padding:0 8%">
<input type="text" id="amount3" style="border:0 none" class="slider_value">

<div id="slider3" class="slider_container" data-value="0" data-min="0" data-max="15" data-steps="1"></div>

<div class="steps">
<?php
for ($i=0, $t=15; $i<=$t ; $i++) {
echo '<span class="tick" style="left:'.(100/$t*$i).'%;';
if ($i==ceil($t/2)) echo 'font-weight:bold;font-size:medium;';
echo '">|<br>'.$i.'</span>';
}
?>
</div>
</div>


.js

$(function(){
var value, step, min, max, input;

$('.slider_container').each(function(){
input = $(this).prev('.slider_value');
value = $(this).data('value');
step = $(this).data('steps');
min = $(this).data('min');
max = $(this).data('max');

$(this).slider({
value: value,
min: min,
max: max,
step: step,
slide: function(event, ui) {
$(this).prev('.slider_value').val(ui.value);
}
});

input.val($(this).slider("value"));
});
});


With a pure html5 slider it's easy to change the slider value:
document.getElementById("slider3").value = '5';
however this does not work with the new code and I can't figure it out.

I have a number of sliders with different IDs. I have an onchange event on a field that fires an AJAX sql search and returns data that I then use to set all the sliders on the page. This all works fine until I added jQuery UI... But only because I don't understand how to select the slider I want to change.

Answer

Turned out not to be so hard:

$(p2).slider({
  value: 0,
  slide: function(event, ui) {
    $(this).prev('.slider_value').val(ui.value); }
});