marcamillion marcamillion - 1 month ago 9
Javascript Question

How to update tag value with the slider updated value

Basically I am trying to implement this.

This is my HTML:

<td>
<p>
<button type="button" class="btn btn-danger m-r-sm" id="slider-step-value">5</button>
Speed
</p>
<div id="basic_slider_1"></div>
</td>


This is how I initialized 4 sliders on my page:

$("#basic_slider_1, #basic_slider_2, #basic_slider_3, #basic_slider_4").noUiSlider({
start: 3,
step: 1,
behaviour: 'tap',
connect: 'upper',
range: {
'min': 1,
'max': 10
},
pips: {
mode: 'steps',
density: 1
}
});


So what I want to happen is, as the value generated by
basic_slider_#
(where
#
can be
1, 2, 3 or 4
), it should update the value of the
slider-step-value
that is related to that
basic_slider_#
.

How do I approach this?

Answer

I think that what you looking for :

var sliders = $('.slider');
var buttons = $('.slider-step-value');

for ( var i = 0; i < sliders.length; i++ ) {
  var button = $(sliders[i]).prev('p').find('button')[0];
  
  noUiSlider.create(sliders[i], {
    start: 3,
    step: 1,
    behaviour: 'tap',
    range: {
      'min':  1,
      'max':  10
    },
    pips: {
      mode: 'steps',
      density: 1
    }
  });
  
  attachEvent(sliders[i], button);
}

function attachEvent(slider,button){
  slider.noUiSlider.on('update', function( values, handle ) {
    button.innerText = parseInt(values[handle]);
  });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/noUiSlider/8.2.1/nouislider.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/noUiSlider/8.2.1/nouislider.min.js"></script>

<p>
  <button type="button" class="btn btn-danger m-r-sm slider-step-value">5</button>
  Speed
</p>
<div class="slider"></div>
<br><br>
<p>
  <button type="button" class="btn btn-danger m-r-sm slider-step-value">6</button>
  Speed
</p>
<div class="slider"></div>