Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't modify innerHTML of a div

I'm trying to modify the innerHTML of a particular div, but I cannot get to erase the content of that div. I have the following code:

<!DOCTYPE html>
<html>
    <head>
        <title>Test</title>
        <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    </head>
    <body>
        <script type="text/javascript">
            function reset() {
                document.getElementById("results").innerHTML = "";
            }
            function check () {
                document.getElementById("results").innerHTML = "foo";
            }
        </script>
        <form name="form1">
            <input type="button" value="Check" onclick="check();">
            <input type="button" value="Reset" onclick="reset();">
        </form>
        <div id="results"></div>
    </body>
</html>

Can anyone point out where I'm doing it wrong?

Thanks in advance.

like image 485
user2064000 Avatar asked Jun 01 '13 17:06

user2064000


2 Answers

That's because there's already a reset function in the form and this function is called instead of your own. Change that name and it will work.

    <script type="text/javascript">
        function r2() {
            document.getElementById("results").innerHTML = "";
        }
        function check () {
            document.getElementById("results").innerHTML = "foo";
        }
    </script>
    <form name="form1">
        <input type="button" value="Check" onclick="check();">
        <input type="button" value="Reset" onclick="r2();">
    </form>
    <div id="results"></div>

Demonstration

This kind of problem is one more reason to avoid inline function calls. A preferred way would be

 <form name="form1">
        <input type="button" value="Check" id=check>
        <input type="button" value="Reset" id=reset>
 </form>
 <div id="results"></div>
 <script type="text/javascript">
       document.getElementById("reset").onclick = function() {
            document.getElementById("results").innerHTML = "";
       }
       document.getElementById("check").onclick = function(){  
           document.getElementById("results").innerHTML = "foo";
       }
</script>
like image 173
Denys Séguret Avatar answered Sep 24 '22 13:09

Denys Séguret


Give

onclick="window.reset();"
like image 43
Diode Avatar answered Sep 25 '22 13:09

Diode