Javascript crash when call getElementById for a not defined input id - Javascript DOM HTML Element

Javascript examples for DOM HTML Element:Input Number

Description

Javascript crash when call getElementById for a not defined input id

Demo Code

ResultView the demo in separate window

<html>
   <head></head>
   <body> 
      <button onclick="myFunction()">Click me</button> 
      <!-- <input type="text" id="demo"></input> --> 
      <script>
function myFunction() {//from   w w w. j  a  v a2s .  c o  m
    var message = undefined;
    
    if (document.getElementById("demo"))
        message = document.getElementById("demo").value;
    if ( message ) 
        console.log(message);
    else 
        console.log("undefined");
}

      </script>  
   </body>
</html>

Related Tutorials