简体   繁体   中英

innerHTML won't print variable

Javascript - I have this code:

<form id="form">A: <input id="k" name="k" step=".1" type="number" value="20" width="5" /></form>

<button onclick = "calc()"> calculate </button>

<script>
function calc() {
var k = document.getElementById("k");
document.getElementById("b").innerHTML = k;
}
</script>
<p id="b"></p>

I get the following message when I press the calculate button:

[object HTMLInputElement]

Why does this not instead print my variable k where the HTML at the bottom is?

您需要元素的.value属性,而不是元素本身。

var k = document.getElementById("k").value;

Because k is an HTMLInputElement , and the toString of HTMLInputElements returns "[object HTMLInputElement]" . If you want to get that element's value then use its value property:

var k = document.getElementById("k").value;

You need to access the value. Right now you are accessing the whole Dom element. You need call k.value

The function is called getElementById() which means it will return an element.

The <input/> element has a .value property that contains the value of the input element, so here is your code working:

<form id="form">A:
    <input id="k" name="k" step=".1" type="number" value="20" width="5" />
</form>

<button onclick="calc()"> calculate </button>

<script>
    function calc() {
        var k = document.getElementById("k");
        document.getElementById("b").innerHTML = k.value;
    }
</script>
<p id="b"></p>

Also, it's recommended to define event functions with JavaScript, to properly sepparate html from js. You can do that by using the Element.addEventListener() function, here is your code now:

<form id="form">A:
    <input id="k" name="k" step=".1" type="number" value="20" width="5" />
</form>

<button id="calcButton"> calculate </button>

<script>
    window.addEventListener("load", function() {
        var btn = document.getElementById("calcButton");
        btn.addEventListener("click", calc);
    });

    function calc() {
        var k = document.getElementById("k");
        document.getElementById("b").innerHTML = k.value;
    }
</script>
<p id="b"></p>

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM