Ila
Ila

Reputation: 3538

Updating JQuery-UI slider from text box value on change()

I have a page with multiple JQuery-UI sliders on it. Each slider has a text input box associated. The association is two-way: when the slider changes, the text box value changes. When the text box value changes, the slider changes.

I have it working one way, so far: when the slider changes the text box value changes. But I can't get it working in reverse.

Here's a JSFiddle with my sliders

Here's the mark-up of one slider:

<label for="amount">A price:</label>
<input type="text" class="amount" id="slider2_amount" />
<div class="slider" id="slider2" data-begin="200" data-end="500"></div>

Here's the JQuery, with which I am trying to grab the value of "amount" and use it to set the value of the associated slider. I am figuring out which slider the text box belongs to by subtracting 7 characters ("_amount") from the end of the text-box ID. This prints out as the correct slider-ID, but I receive the error "Object #slider2 has no method 'slider'".

$('.amount').change(function() {
    var value = $(this).attr("value"),
        selector = ("#" + $(this).attr("id").slice(0,-7));
        selector.slider("value", value);
})  

Is there a better way to figure out the relationship between the text box and the slider on a page that will contain many of both? Or, can you see another reason why this is not working?

__

Update: I am trying to follow the model used in the Hotel Rooms demo on JQueryUI, but their mark-up assumes one instance of slider per page.

Upvotes: 2

Views: 5862

Answers (2)

sjmog
sjmog

Reputation: 161

Try this:

$('.amount').change(function() {
    var value = $(this).attr("value"),
    selector = ("#" + $(this).attr("id").slice(0,-7));
    selector.val(value);
    selector.slider('refresh');
}) 

Upvotes: 0

Sergio
Sergio

Reputation: 28837

Here is a suggestion:

$('.amount').change(function () {
    var value = this.value,
        selector = $(this).parent('p').next();  
    selector.slider("value", value);
})

Demo here

And using your idea, the correction is: selector = $("#" + this.id.split('_')[0]);
This demo here

Upvotes: 3

Related Questions