'Getting value of the ID "name" always returns undefined [duplicate]

When I retrieve the value of the ID "name" it always returns undefined. I used document.getElementById("name").value; but it was still showing an undefined error.

const value = document.getElementById("name").value;
console.log(value);
<input type =text" id="name">
 


Solution 1:[1]

Did you try this?


<!-- ... -->

<input id="some_id" type="text" />

<!-- ... -->

<script>
  let el = document.getElementById('some_id');
  let value = el.value;
</script>

Solution 2:[2]

It's returning with no value as it gets and logs the value from the start which shows nothing. In my example, I fixed it by adding a button to prevent this:

function getval() {
console.log(document.getElementById("name").value);
}
<input type="text" placeholder="Enter name.." id="name">
<button onclick="getval()">Get value</button>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 MetallimaX
Solution 2