-1

below the this text is my code It works well when i input empty / low num / high num however when i input string it doesn't work well

    <!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <h1>Show error message depending on input value by using try/catch/throw</h1>
    <input type="text" id="input1">
    <button id="btn1" onclick="showR()">Show the result</button>
    <p id="demo1"></p>

    <script type="text/javascript">
        function showR(){
        var x;
        x= document.getElementById('input1').value;
        //x= Number(x);
        try{
            if(x=="")throw "empty";
            if(x==isNaN(x))throw "not a number";
            x= Number(x);
            if(x<5)throw "too low";
            if(x>10)throw "too high";
            document.getElementById(demo1).innerHTML=x;
        }catch(err){
            document.getElementById('demo1').innerHTML = "input is : " + err;
        }
        document.getElementById('input1').innerHTML='hi';
    }
    </script>
</body>
</html>

the error message is input is : TypeError: Cannot set property 'innerHTML' of null what is the reason and how can i resolve this problem

1 Answers1

2
document.getElementById(demo1).innerHTML=x;

this should be changed to

document.getElementById('demo1').innerHTML=x;

First, Learn to read the error.

tomision
  • 964
  • 9
  • 22
  • 1
    "First, Learn to read the error." Great advice but maybe the OP is looking for how to find the error hence posting here.... Maybe advice to check the browser console? – NewToJS Aug 02 '16 at 03:44
  • @NewToJS Thanks for the **The wisdom of the answer** – tomision Aug 02 '16 at 03:55
  • [judge variable is Number](http://stackoverflow.com/questions/18082/validate-decimal-numbers-in-javascript-isnumeric) – tomision Aug 02 '16 at 04:03