user3442701 user3442701 - 4 months ago 11
Javascript Question

Unable to read input DOM element's value

i have following html/JS code :

function controller()
{
document.write(document.getElementById("name").value) ;
document.write(document.getElementById("id").value) ;
}


<input type="text" id="name"/>
<input type="text" id="id"/>
<input type="button" id="push" onclick="controller()"/>


Problem : when i click on push button
onclick
is fired and
controller
function is executed and i am able to retrieve value of element having id
name
but the second element having id
id
is not read and as a result i get the following error for second input element :


Uncaught TypeError: Cannot read property 'value' of null


I have been struggling for hours but i am unable to understand where i am making mistake can somebody help ?

Answer

Your script read the inputs values correctly, but when the first document.write statement execute it will override the body so when the script try to execute the second one it will find no input and return the error line :

Uncaught TypeError: Cannot read property 'value' of null

Hope this helps.

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