问题描述:

I don't know why it doesn't work. How can i retrieve the input value?

<body>

<script>

function toCelsius() {

var g = document.getElementById("f").innerHTML;

var b = (5/9) * (g-32);

}

document.getElementById("demo").innerHTML = b;

</script>

Fahrenheit = <input id="f" type=text size=6>

<input type=button value="Bereken" onClick="toCelsius()">

<p id="demo"></p>

</body>

网友答案:

This line:

document.getElementById("demo").innerHTML = b;

Runs when:

  • when demo doesn't exist in the document
  • when b hasn't been defined
  • where b is out of scope (because b is defined inside the function)

You need to move that line inside the function

This line:

var g = document.getElementById("f").innerHTML;

… tries to read the children of an input element, but inputs are void elements: They don't have children.

You need to read the value of the input instead.

<body>
  <script>
    function toCelsius() {
      var g = document.getElementById("f").value;
      var b = (5 / 9) * (g - 32);
      document.getElementById("demo").innerHTML = b;
    }
  </script>

  Fahrenheit =
  <input id="f" type=text size=6>
  <input type=button value="Bereken" onClick="toCelsius()">

  <p id="demo"></p>
</body>
网友答案:

First, the "script" tag should be left before closing the body.

To retrieve the value of input, use document.getElementById("f").value;

See my example: http://codepen.io/joaocarvalhowd-1472219370/pen/apMywY

网友答案:

The innerHTML property is part of the Document Object Model (DOM) that allows Javascript code to manipulate a website being displayed. Specifically, it allows reading and replacing everything within a given DOM element (HTML tag)

To get the value from a input field you need to use

var your_var = document.getElementById("filed-id").value;

So, your final code will be as follows:

<body>
    <script>
    function toCelsius() {
        var g = document.getElementById("f").value;
        var b = (5/9) * (g-32);
    }
    document.getElementById("demo").innerHTML = b;
    </script>

                    Fahrenheit = <input id="f" type=text size=6>
                    <input type=button value="Bereken"         onClick="toCelsius()"> 

                    <p id="demo"></p>
</body>
相关阅读:
Top