-2

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">
 
Sam Perez
  • 1
  • 2
  • `name` is not `id` – Dai Dec 11 '20 at 16:55
  • I don’t see that your input has an id with a value of “name”. Also you getElementById syntax is incorrect. – Jacobo Dec 11 '20 at 16:56
  • I converted your code into a live demo and it runs without errors (although since there is no value, it logs an empty string). "showing undefined ereor" is *very* vague through, you should quote the exact error message. – Quentin Dec 11 '20 at 16:58
  • See also [Why does jQuery or a DOM method such as getElementById not find the element?](https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) – Heretic Monkey Dec 11 '20 at 17:00

2 Answers2

-1

Did you try this?


<!-- ... -->

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

<!-- ... -->

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

MetallimaX
  • 594
  • 4
  • 13
-3

Give it an id to query by ID:

<input type =text" id="name">

then retrieve it by

document.getElementById("name").value
KienHT
  • 1,098
  • 7
  • 11
  • 1
    Your code appears to be identical to the code in the question. You didn't even fix the rogue `"` (which has no effect on the code running successfully). – Quentin Dec 11 '20 at 16:58
  • He just editted it – KienHT Dec 11 '20 at 17:00
  • He got it undefined because he queried the value right when he declared it, when the input is empty – KienHT Dec 11 '20 at 17:04
  • An empty string is neither undefined nor an error. – Quentin Dec 11 '20 at 17:05
  • That's what he got! – KienHT Dec 11 '20 at 17:05
  • The OP **said** they got an error. https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element is probably a duplicate but the OP hasn't provided a reproducable test case or quoted the actual error message they are getting. – Quentin Dec 11 '20 at 17:06