Search code examples
javascripthtmlvariableshref

use javascript variable in href went wrong - why?


there are many Questions and Answers out there for how to get a Javascript Variable into the href tag, but I am running into a Problem which no one seems to have.

I have a slider and depending on what position the slider is set, the value should be taken into the href.

So if the sliders value is 50 the link should be "http//testurl.de/50" However I get always back "http://testurl.de/[object%20HTMLSpanElement]" And don't know what's wrong.

<div class="slidecontainer">
<input type="range" min="1" max="100" value="50" class="slider" id="ValueSlider">
  <p>Value: <span id="SetValue"></span></p>
</div>



<script>
  var slider = document.getElementById("ValueSlider");
  var output = document.getElementById("SetValue");
  output.innerHTML = slider.value;

  slider.oninput = function() {
  output.innerHTML = this.value;
  }

</script>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​



<a href="#" onclick="window.location='http://testurl.de/' + SetValue">link</a>

Any help would be much appreciated! :) Best Mo


Solution

  • You have two ways to fix this, and you actually do them both already a few lines above that code.

    • SetValue is the ID of your span element, so to get the data from that element, you can use SetValue.innerHTML, SetValue.innerText or a few others.
    • Or, you can just reference the input element you have there (looks like you call it slider) and grab slider.value again.

    <a href="#" onclick="window.location='http://testurl.de/' + SetValue.innerHTML">link</a>
    // or
    <a href="#" onclick="window.location='http://testurl.de/' + SetValue.innerText">link</a>
    // or
    <a href="#" onclick="window.location='http://testurl.de/' + SetValue.textContent">link</a>
    // or
    <a href="#" onclick="window.location='http://testurl.de/' + slider.value">link</a>