Search code examples
javascripthtmlvisual-web-developer

error in printing the variable in javascript


When I'm running this code it is not showing me the message which I want to display (i.e: res).Suppose I'm giving an input "$code$".Can anyone just help me out?

<!DOCTYPE HTML>
<html>
<head>

</head>
<body>
    <h1>Enter a sample message</h1>
    <form>
        <input type="text" name="a" id="a">
        <button onclick="parse()">submit</button>
        <p id="a"></p>
    </form>
    <script>
        function parse(){
            var msg=document.getElementById("a").innerHTML;
            var res=msg.replace("$code$","1101"); 
            document.getElementById("a").innerHTML=res;//this is to print res.

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

Solution

  • Two elements can't have the same ID. Further, an input element's value can not be obtained using the innerHTML property. Also, on clicking the submit button, the page will reload since the form get's submitted. To prevent that, call the function parse in an onsubmit on the <form> tag, and return false from the function.

    <!DOCTYPE HTML>
    <html>
    <head>
    
    </head>
    <body>
        <h1>Enter a sample message</h1>
        <form onsubmit="return parse();">
            <input type="text" name="a" id="a">
            <button type="submit">submit</button>
            <p id="b"></p>
        </form>
        <script>
            function parse(){
                var msg = document.getElementById("a").value;
                document.getElementById("b").innerHTML = msg;
                return false;
            }
        </script>
    </body>
    </html>