oe a
oe a

Reputation: 2280

cannot access elements inside function

I cannot get jquery to access elements inside of an event function:

JSFiddle: https://jsfiddle.net/w3zv5t0s/2/

On page load, in document.ready you can see the slider go to 10. However, on a toggle switch, nothing happens, it should go to 1.

JS:

$(document).ready(function() {

   //WORKS HERE
   $(".dimmerSlider").val(10).slider("refresh");

   $('.toggle').on("slidestop", function() {

    //NOT HERE
        $(".dimmerSlider").val(1).slider("refresh");

   });

 });

HTML:

<select class='toggle' id='3' data-role='slider' data-itemID='3'>
  <option value='ON'>On</option>
  <option value='OFF' selected='selected'>Off</option>
</select>

<input class='dimmerSlider' type='range' id='3' value='15' min='0' max='15' step='1' data-highlight='true' data-itemID='sl3' />

Upvotes: 2

Views: 41

Answers (2)

user2182349
user2182349

Reputation: 9782

It looks like you are using a range input with a jQueryUI slider.

If you want to use the slider widget, according to the documentation at http://api.jqueryui.com/slider/, you'd probably use a div and instantiate it with an option setting the value. You would then use the slider calls to make further updates. Be sure to include the jQuery UI code with your page.

<select class='toggle' id='3' data-role='slider' data-itemID='3'>
  <option value='ON'>On</option>
  <option value='OFF' selected='selected'>Off</option>
</select>

<div class='dimmerSliderDiv'></div>

<input class='dimmerSliderInput' type='range' id='3' value='15' min='0' max='15' step='1' data-highlight='true' data-itemID='sl3' />

 $(document).ready(function() {
 $(".dimmerSliderDiv").slider({
   "value": 10
 }); $(".dimmerSliderInput").val(10);
   $('.toggle').on("change", function() {
       $(".dimmerSliderDiv").slider("option", "value", ($(this).val() === "OFF") ? 0 : 15);
       $(".dimmerSliderInput").val(($(this).val() === "OFF") ? 0 : 15);
   });
 });

If you are planning to use the range input, you would use the val method to set the value.

Upvotes: 1

DinoMyte
DinoMyte

Reputation: 8868

You need to delegate the change event ( instead of slidestop ) before you invoke the slider function.

 $(document).ready(function() {

    $('.toggle').on("change", function() {
      $(".dimmerSlider").val(1).slider("refresh");    
   });

   $(".dimmerSlider").val(10).slider("refresh");
 });

Working example : https://jsfiddle.net/DinoMyte/w3zv5t0s/3/

Upvotes: 2

Related Questions