Reputation: 2282
This works fine but when I have two sliders, the javasctript causes problems because both have the same id "range". How can I modify the js to allow two sliders to be on the same page? Thanks
<li>
<label for="budget">Budget*</label>
<input type="range" min="1000" max="10000" value="2000" step="1000" onchange="showValue(this.value)">
<span id="range">$2000</span>
<script>
function showValue(newValue)
{
document.getElementById("range").innerHTML=newValue;
}
</script>
</li>
Upvotes: 0
Views: 110
Reputation: 45589
The solution is to use classes instead of ids.
Also, do not mix vanilla JavaScript with jQuery in this way. If you are using jQuery use it anywhere you will interact with manipulate the DOM.
1. HTML:
<li>
<label for="budget">Budget*</label>
<input type="range" min="1000" max="10000" value="2000" step="1000">
<span class="range">$2000</span>
</li>
<li>
<label for="budget">Budget*</label>
<input type="range" min="1000" max="10000" value="2000" step="1000">
<span class="range">$2000</span>
</li>
2. jQuery:
$(document).ready(function(){
$('input[type="range"]').change(function(){
var $this = $(this),
$li = $this.closest('li');
$li.find('span.range').text('$'+$this.val());
});
});
3. Demo
Upvotes: 0
Reputation: 25198
Two Items should never have the same id. That's what classes are for.
Also, if you're using jQuery, you can condense this code to:
$("#range").html(newValue);
Upvotes: 4