Ibanez1942
Ibanez1942

Reputation: 1

Changing Text in Javascript

I am not asking anybody to code for me. Please just tell me what I am missing or what I have done wrong with my codes.

My javascript program should run like this:

  1. Upon pressing a button, a simple multiplication table should appear and overwrite the words "The Table should be here".
  2. Pressing another button, another simple multiplication button should appear and overwrite the previous multiplication table.

I am able to make the multiplication tables come out but the problem is, it does not overwrite the previous table. It just creates another table at the bottom of the previous one. Please Help. This is not a home work.. I am very new and just trying to learn all the possibilities of creating a somewhat complex program using simple codes.

<script type="text/javascript">
    function x()
    {
        var a=1;
        for(a=0;a<=10;a++)
        {
            var total = 2 * a;
            var newHeading = document.createElement("p");
            var h1Text = document.createTextNode("2 x " + a + " = " + total);
            newHeading.appendChild(h1Text);
            document.getElementById("dname1").appendChild(newHeading);
        }
    }

    function y(total)
    {
        var a=0;
        for(a=0;a<=10;a++)
        {
            var total = 3 * a;
            var newHeading = document.createElement("p");
            var h1Text = document.createTextNode("3 x " + a + " = " + total);
            newHeading.appendChild(h1Text);
            document.getElementById("dname2").appendChild(newHeading);
        }
    }
    </script>
    </head>
    <body>

    <h1>Date and Hours</h1>
   <p>Click a button</p>
   <p id="dname1">Table of 2 should be here</p>
    <p id="dname2">Table of 3 should be here</br></p>

   <button type="button" onclick="x()">Table of Two</button>
   <button type="button" onclick="y()">Table of Three</button>

Upvotes: 0

Views: 185

Answers (2)

jamesfzhang
jamesfzhang

Reputation: 4501

if you want to use jQuery, simply do this

$("#dname1").html("");
$("#dname2").html("");

Upvotes: -1

pimvdb
pimvdb

Reputation: 154968

You should clear both tables before appending anything: http://jsfiddle.net/2NtXH/2/.

// setting the innerHTML to an empty string basically removes its contents
document.getElementById("dname1").innerHTML = "";
document.getElementById("dname2").innerHTML = "";

Upvotes: 3

Related Questions