You have selected the wrong element. I believe you're trying to select the
<input>
element not the
<button>
element. If you change
let string = document.getElementById("inputbutton").value;
to
let string = document.getElementById("text").value;
and it should work. The reason is that the button element doesn't support the value property. Check on w3schools' HTML DOM element table for more information.
Here is the fixed code with runnable example:
function startFunction() {
let string = document.getElementById("text").value;
console.log(string);
}
<input id="text" placeholder="Type Something" maxlengh="50">
<button id="inputbutton "onclick="startFunction()">Submit</button>
Here are few things to remember:
- Do not load the script before the document. For example, the following code will give you an error:
<script>
document.getElementById('d').innerHTML = "Hello";
</script>
<div id="d">
</div>
- To fix such problem, put the script after the HTML element you're trying to work with. The following code will not throw an error:
<div id="d">
</div>
<script>
document.getElementById('d').innerHTML = "Hello";
</script>
This is because the browser execute code line by line in the same order as it is written. For the first example, the script is executed before the
<div>
element is fully loaded. So, when the browser encounters the code, it can not find the
<div>
element by ID.