-2
 document.getElementById("name").value = data;

it shows Uncaught TypeError: Cannot set property 'value' of null. why is this happen?

the data have the value.

  • 2
    That means no element with id 'name' exists in the DOM – DinoMyte Feb 03 '16 at 03:57
  • 1
    It means that `document.getElementById("name").value` is `null`, not `data`. You have no element with the id `name` in your HTML – p4sh4 Feb 03 '16 at 03:58
  • 2
    Most probably `document.getElementById("name")` is returning a `null`, do you have an element by the name "name" in your HTML form? Also you should consider changing it as "name" would conflict with reserved words.. – vmachan Feb 03 '16 at 03:58
  • 4
    ^^^ and that also means the code is executing before the element exists in DOM – Tushar Feb 03 '16 at 03:58
  • 1
    try to write the script after body of document. – anshabhi Feb 03 '16 at 03:59
  • thanks for suggestion. i put the ` – Ismael Bin Azman Feb 03 '16 at 04:02
  • You can still put the script before the body. All you have to do is to wrap the JavaScript statements inside window.onload function – DinoMyte Feb 03 '16 at 04:09

1 Answers1

0

You're receiving that error because there doesn't exist an element if an ID of name when that piece of JavaScript is executing.

document.getElementById("name") is returning null since no element is found with the specified ID. You then attempt to access the property value of null, which doesn't exist.

What's most likely happening is your JavaScript code is executing before the element exists (move your script to the end of the body or inside a document ready function, or you mis-typed the ID.

michael
  • 737
  • 4
  • 10