0

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>
0

2 Answers 2

3

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 = "";
Sign up to request clarification or add additional context in comments.

Comments

-1

if you want to use jQuery, simply do this

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

2 Comments

I don't know jQuery yet. I'm trying to learn the basics of Javascripts first.
If he is new to javascript he should be doing it in javascript not a framework. much better to move onto a framework once you understand whats going on at the lower levels.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.