0

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>
Tessmore
  • 1,054
  • 1
  • 9
  • 23
user852974
  • 2,242
  • 10
  • 41
  • 65

2 Answers2

4

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);

switz
  • 24,384
  • 25
  • 76
  • 101
  • 1
    +1 for clear statement, and for pointing out that the OP wasn't using jQuery in the code he showed us. – JCOC611 Nov 19 '11 at 23:47
0

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

Shef
  • 44,808
  • 15
  • 79
  • 90
  • 2
    I take serious issue with the last two sentences. There are absolutely times when it is appropriate to use vanilla JS instead of jQuery. http://stackoverflow.com/questions/4651923/when-to-use-vanilla-javascript-vs-jquery – Matt Ball Nov 19 '11 at 23:48
  • I agree. Vanilla JS is vital when developing any jQuery website. Maybe not in the scenario above, but there are tons of times when it is applicable. – switz Nov 19 '11 at 23:49
  • @MattBall & Switz: I should have made the statement more clear, but what I was saying is that if you want to manipulate the DOM use jQuery. I agree with you, it is inefficient and overuse when you just need to retrieve from an element you already have a reference of. – Shef Nov 19 '11 at 23:53
  • This works except how do I modify it If I want the second slider to be in some other type of units (e.g "weeks" instead of "$") – user852974 Nov 20 '11 at 00:02
  • @user852974 Add the unit on another span element, [like this](http://jsfiddle.net/Shef/P39xB/). – Shef Nov 20 '11 at 00:04