Tommy Lee
Tommy Lee

Reputation: 794

Passing value from input to SVG attributes via JavaScript

Below are my codes

<!DOCTYPE html>
<html>
  <body>
    <svg width="12cm" height="12cm" viewBox="0 0 400 400" xmlns="http://www.w3.org/2000/svg">
    <line x1="20" y1="20" x2="20" y2="300" stroke="red"/>
    <line x1="20" y1="300" x2="300" y2="300" stroke="red"/>
    <rect id="bar1" x="40" y="280" width="30" height="20"/>
    <rect id="bar2" x="100" y="260" width="30" height="40"/>
    <rect id="bar3" x="160" y="180" width="30" height="120"/>
    <rect id="bar4" x="220" y="240" width="30" height="60"/>
    </svg>

    <br>
    <input id="input">
    <input id="button1" type="button" value="Set Value" onclick="setHeight()"/>
    <script>
       function setHeight(){
        var value1 = document.getElementById("input").getAttribute("value");
        var value2 = parseFloat(value1);
        document.write(value2);
        document.getElementById("bar2").setAttribute("height", value2);
       }
    </script>
  </body>
</html>

I'm trying to pass the value of "input" into the "height" of "bar2". But something is wrong in the script that the "input" is not converted to int value.

Thanks

Upvotes: 1

Views: 1746

Answers (1)

Nick Rolando
Nick Rolando

Reputation: 26167

Try getting input value like this

var value1 = document.getElementById("input").value;

and setting it to bar2 like this

document.getElementById("bar2").style.height = value2 + 'px';

Upvotes: 1

Related Questions