Barrett Kuethen
Barrett Kuethen

Reputation: 1914

How do I set the value of a jquery slider on load if it's already set

I have a jquery slider and a textbox that stores the value. I'm running an asp.net application and want to load the textbox with the value if one is already stored and have the slider reflect the value. I'm thinking that a simple if statement in the jquery would do it, but i'm unfamiliar with the function.

Here is my current jquery:

    $("#cultureSlider").slider({
    value: 50,
    min: 1,
    max: 100,
    step: 1,
    slide: function (event, ui) {
        $(".cultureScore").val("" + ui.value);
    }
});

I would think something like this would work (but it doesn't):

    $("#cultureSlider").slider({
    if($(".cultureScore").val() == 50){
       value: 50,
    } else {
       value: $(".cultureScore").val(),
    }
    min: 1,
    max: 100,
    step: 1,
    slide: function (event, ui) {
        $(".cultureScore").val("" + ui.value);
    }
});

Upvotes: 0

Views: 912

Answers (3)

Traveling Tech Guy
Traveling Tech Guy

Reputation: 27849

Why not do this:

var myVal = ($(".cultureScore").val() == 50) ? 50 : $(".cultureScore").val();
$("#cultureSlider").slider({
    value: myVal,
.
.
.

Upvotes: 0

Clive
Clive

Reputation: 36955

I'm pretty sure an if statement is invalid where you've got it, and I think your check is redundant anyway, whether the if results in TRUE or FALSE you're always going to use $(".cultureScore").val():

$("#cultureSlider").slider({
  value: $(".cultureScore").val(),
  min: 1,
  max: 100,
  step: 1,
  slide: function (event, ui) {
    $(".cultureScore").val("" + ui.value);
  }
});

Upvotes: 3

Joseph Marikle
Joseph Marikle

Reputation: 78560

I think your syntax is wrong... try either an inlined if (forgot the technical term) or performing the calculation outside the slider instantiation.

Method one

$("#cultureSlider").slider({
    value: ($(".cultureScore").val() == 50 ? 50 : $(".cultureScore").val()),
    min: 1,
    max: 100,
    step: 1,
    slide: function (event, ui) {
        $(".cultureScore").val("" + ui.value);
    }
});

Method two

var scoreVal = 0;
if($(".cultureScore").val() == 50)
    scoreVal = 50;
else
    scoreVal = $(".cultureScore").val();

$("#cultureSlider").slider({
    value: scoreVal,
    min: 1,
    max: 100,
    step: 1,
    slide: function (event, ui) {
        $(".cultureScore").val("" + ui.value);
    }
});

Upvotes: 2

Related Questions