Phil.Wheeler
Phil.Wheeler

Reputation: 16858

Unable to get index from jQuery UI slider range

I'm having a hell of a time trying to get (what I thought was) a simple index from a collection of multiple sliders. The HTML is as follows:

<div id="left-values" class="line">
    <span id="l1" style="padding: 0 1.8em;">0</span>
    <span id="l2" style="padding: 0 1.8em;">0</span>
    <span id="l3" style="padding: 0 1.8em;">0</span>
    <span id="l4" style="padding: 0 1.8em;">0</span>
    <span id="l5" style="padding: 0 1.8em;">0</span>
    <span id="l6" style="padding: 0 1.8em;">0</span>
    <span id="l7" style="padding: 0 1.8em;">0</span>
    <span id="l8" style="padding: 0 1.8em;">0</span>
</div>

And the jQuery code is:

    // setup audiometry sliders
    $("#eq > span").each(function (e) {
        // read initial values from markup and remove that
        var value = parseInt($(this).text());
        // var index = $(this).index; <- this didn't work.

        $(this).empty();
        $(this).slider({
            value: value,
            slide: function (event, ui) {
                //console.log($(this).attr('id')); <- neither did this.
                //console.log(index);
                $('#left-values span:first').text(ui.value);
            }
        })
    });

The problem is that jQuery UI - when creating a slider - replaces the existing HTML with its own markup. This includes any ID values and, for whatever reason, I can't get the index for a given slider to surface either. So I'm running out of ideas.

Upvotes: 2

Views: 1987

Answers (2)

Nick Craver
Nick Craver

Reputation: 630579

What you have works, maybe you have something else going on. Here's a stand-alone sample, watch the console for output: http://jsfiddle.net/FBh3a/1/

$("#eq > span").each(function (e) {
    var value = parseInt($(this).text());    
    $(this).empty();
    $(this).slider({
        value: value,
        min: -10,
        max: 10,
        slide: function (event, ui) {
          console.log($(this).attr('id')); //<- works here, outputs l1, l2, etc
          console.log($(this).index()); //outputs 0, 1 .... 7 (0-based index)
        }
    });
});​

Upvotes: 1

karim79
karim79

Reputation: 342695

You can get the index like so:

$("#eq > span").each(function (index, Element) {
    alert(index);
    ...

see http://api.jquery.com/each/

Upvotes: 2

Related Questions