views:

59

answers:

2

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.

+2  A: 

You can get the index like so:

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

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

karim79
Un-bloody-believable. I spent too much time faffing around with the jQuery UI stuff, I completely forgot about the calling function. Someone want to downvote me for failing to RTFM? Thanks for the pointer.
Phil.Wheeler
A: 

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)
        }
    });
});​
Nick Craver