I have a page with multiple range sliders. I would like to control the output based on the value. Is there away to make this function work for multiple sliders on the same page? or do I have to re-write the function over again with new IDs for each input?
Code:
$(".slider").mousemove(function () {
if ($(this).val()==this.min) {
$(".priceOutputId").text("Less than $80")
}
else if ($(this).val()==this.max) {
$(".priceOutputId").text("More than $100")
}
else {
$(".priceOutputId").text("around $" + $(this).val())
}
}
)
<label class="radio_title">
<input type="range" min="80" max="100" value="80" class="slider" id="priceInputId">
<div class="range_output">
<output name="priceOutputName" class="priceOutputId">Less Than $80</output>
</div>
</label>
<label class="radio_title">
<input type="range" min="80" max="100" value="80" class="slider" id="priceInputId">
<div class="range_output">
<output name="priceOutputName" class="priceOutputId">Less Than $80</output>
</div>
</label>
To make the output relevant to only the element which raised the event you need to hook the logic to the this
reference. From there you can use jQuery's DOM traversal methods, such as closest()
and find()
to retrieve the relevant elements and update them.
Also note that you cannot use the same id
attribute multiple times. They must be unique. If you want to group elements by behaviour use a class
. In addition, the input
event is more appropriate for a range slider control, as it also works when the controls value is changed via the keyboard.
With all that said, try this:
$(".slider").on('input', function() {
let $label = $(this).closest('label');
let $output = $label.find('.priceOutput');
if (this.value == this.min) {
$output.text("Less than $80")
} else if (this.value == this.max) {
$output.text("More than $100")
} else {
$output.text("around $" + this.value)
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label class="radio_title">
<input type="range" min="80" max="100" value="80" class="slider priceInput">
<div class="range_output">
<output name="priceOutputName" class="priceOutput">Less Than $80</output>
</div>
</label>
<label class="radio_title">
<input type="range" min="80" max="100" value="80" class="slider priceInputId">
<div class="range_output">
<output name="priceOutputName" class="priceOutput">Less Than $80</output>
</div>
</label>
Also note that the if
condition can be shortened using the following ternary. I'll leave it to your choice whether you prefer the brevity over the ease of reading:
let output = this.value === this.min ? 'Less than $80' : this.value === this.max ? 'More than $100' : 'Around $' + this.value;
$output.text(output);