简体   繁体   中英

jQuery UI slider: multiple sliders with default values

I have a page with multiple jQuery UI sliders on it. The sliders need to have a default value. For example, when somebody comes to my form, sets the slider, submits the form but they get an error the sliders should not reset back to 0. All of the previous elements of my form that they filled out should remain in place. I know you can set a default value for the slider but I'm having trouble getting it to work with multiple sliders.

What I'm looking to do is take the value from the input field and use that as the default value for the range slider. You can see at the jsfiddle below I have the input's value's set to 2 and 4. When you load the page the sliders both go to the same position at 2.

Somehow I need to tell the slider to get the value of the input that is directly below it and use that as the default.

Any ideas on how to do this?

http://jsfiddle.net/dmcgrew/EquTn/3/

HTML:

<div class="kpa_rate kpa_rate1">
    <label for="kpa1_rating_value">Rating 1:</label>

    <div id="1" class="slider"></div>
    <input type="text" class="kpa1_rating_value" name="kpa1_rating" value="2" />       
</div>


<div class="kpa_rate kpa_rate2">
    <label for="kpa2_rating_value">Rating 2:</label>

    <div id="2" class="slider"></div>
    <input type="text" class="kpa2_rating_value" name="kpa2_rating" value="4" />
</div>

JS:

$(function() {
    $( ".slider" ).slider({
 range: "max",
 min: 0,
 max: 5,
 value: $("input", this).val(),
 slide: function( event, ui ) {                 
     //get the id of this slider
     var id = $(this).attr("id");
     //select the input box that has the same id as the slider within it and set it's value to the current slider value. 
         $("span[class*=" + id + "]").text(ui.value);
     $("input[class*=" + id + "]").val(ui.value);
 }
 });
});

Replace your value option with the create event:

create: function () {
    $(this).slider( "option", "value", $(this).next().val() );
},

jsFiddle example

Best answer from jQueryUI itself multiple sliders

<div id="eq">
  <span>88</span>
  <span>77</span>
  <span>55</span>
 </div>

// Script
$( "#eq > span" ).each(function() {

  // read initial values from markup and remove that
  var value = parseInt( $( this ).text(), 10 );

  $( this ).empty().slider({
    value: value,
    range: "min",
    animate: true,
    orientation: "vertical"
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM