Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get dynamic value of input element with d3?

Tags:

d3.js

I have an input element of type text with id "msg". I click the button to get value of above input element. First time I succeed. After change the value of above input element from 10 to 13, click the button again, this time I fail in get modified value by D3. Why? My html file is as follows:

    <!DOCTYPE html>
    
    <html lang="en">
    <head>
        <meta charset="utf-8" />
        <title></title>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js">            </script>

        <script>
            function getMessage() {
                d3.select("#d3").html("D3:"+d3.select("#msg").attr("value"));
                document.getElementById("dom").innerHTML = "DOM:" + document.getElementById("msg").value;
            }
        </script>
    </head>
    <body>
        <p>
            <form>
                <input type="text" value="10" id="msg" >
            </form>
        </p>
        <p>
            <button onclick="getMessage()">Get Message</button>
        </p>
        <p id="d3">

        </p>

        <p id="dom">
        </p>
    </body>
    </html>
like image 910
hjyanghj Avatar asked Jul 12 '15 15:07

hjyanghj


1 Answers

The value attribute is the default value, you need to access the value property
So, change this...

d3.select("#d3").html("D3:"+d3.select("#msg").attr("value"));  

to this...

d3.select("#d3").text("D3:"+d3.select("#msg").property("value"));  

or this...

d3.select("#d3").text("D3:"+d3.select("#msg").node().value);

Working code

<head>
  <meta charset="utf-8" />
  <title></title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js">
  </script>

  <script>
    function getMessage() {
      d3.select("#d3").text("D3a:" + d3.select("#msg").property("value"));
      d3.select("#d3node").text("D3b:" + d3.select("#msg").node().value);
      document.getElementById("dom").innerHTML = "DOM:" + document.getElementById("msg").value;
    }
  </script>
</head>

<body>
  <p>
    <form>
      <input type="text" value="10" id="msg">
    </form>
  </p>
  <p>
    <button onclick="getMessage()">Get Message</button>
  </p>
  <p id="d3">

  </p>
  <p id="d3node">

  </p>

  <p id="dom">
  </p>
</body>

</html>
like image 87
Cool Blue Avatar answered Oct 13 '22 03:10

Cool Blue