-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">
 
alt-codes
  • 1
  • 3
Sam Perez
  • 1
  • 1
  • `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

3 Answers3

-1

Did you try this?


<!-- ... -->

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

<!-- ... -->

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

MetallimaX
  • 596
  • 3
  • 12
-1

Uh, not really how you do it, as it should have an id. It's returning undefined since it can't find anything. Also you should get an error since it can't be found in your logs. Try this example:

function getval() {
document.getElementById("text").innerText = document.getElementById("inputtext").value;
}
<input type="text" placeholder="Enter name.." id="inputtext">
<button onclick="getval()">Get value</button>
<p id="text"></p>
alt-codes
  • 1
  • 3
-3

Give it an id to query by ID:

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

then retrieve it by

document.getElementById("name").value
KienHT
  • 454
  • 2
  • 9
  • 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