Jason
Jason

Reputation: 11363

Get ID of slider element activated in jQuery.each()

I have a number of sliders defined in a container div like

  <div id="opacitySlider" class='slider'>
    <div class="sliderText">Fade Opacity</div>
    <div id="fadeVal"></div>
  </div>

and many more

They are controlled by the jQuery UI slider() functionality defined as

$(".slider").each(function(e){
  $(this).slider({
    value: 50,
    orientation: 'horizontal',
    animate: true,
    range: 'min',
    slide: function(e, ui){
      console.log($(e).id);
      console.log($(this).id;
    }
  });
});

What I want to do is update the slider value div with the value of the associated slider

Both the console logging statements return undefined. I need to know the ID of the slider that's firing off the events to update the correct div element. How can I do this?

Upvotes: 0

Views: 2402

Answers (4)

adeneo
adeneo

Reputation: 318312

.each() has two arguments, the first being the index, the second being the element:

$(".slider").each(function(i, e) {
    $(e).slider({
        value: 50,
        orientation: 'horizontal',
        animate: true,
        range: 'min',
        slide: function(e, ui) {
            console.log(this.id); //new scope
        }
    });
});​

When doing only $(".slider").each(function(e) {...}, then e will be the index and not the element, so you are trying to get the ID for the numbers 0, 1, 2 etc.

Upvotes: 2

Dennis
Dennis

Reputation: 32608

Use the id property of this or e.target:

slide: function(e, ui){
  console.log(this.id);
  //or
  console.log(e.target.id);
}

jsFiddle

Upvotes: 0

cosmic_wheels
cosmic_wheels

Reputation: 44

Try this:

$(".slider").each(function(e){

  var curSlider = $(this);

  $(this).slider({
    value: 50,
    orientation: 'horizontal',
    animate: true,
    range: 'min',
    slide: function(e, ui){

      console.log(curSlider.attr('id'));

    }
  });
});

Upvotes: 0

Andy
Andy

Reputation: 30135

Should be $(this).attr('id'); or $(e).attr('id');

Upvotes: 0

Related Questions