Creating an HTML table on-the-fly leads to the opening of a fresh new webpage

Has anyone encountered this issue before? I have a math table coding function, which runs when a button is clicked. However, when I click the button, the table appears on a new page instead of on the same page.

    <!doctype html>
<html>
<head>
    <title>Times Tables Trainer</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <section id="content">
    <p>Do you want to practice your times tables? Click the practice button below.</p>
    <button id="practice" name="practice" value="practice" onclick='practice()';>Practice Times Tables!</button>
<div id="1">
    <script type='text/javascript'>
    function practice(){
            var num = prompt("Enter a number", "0");
            var num1 = parseInt(num); 

                for(i= 1; i< 11; i++) {
                    document.writeln("<table border='1'><tr><td>" + i + " x " + num1 + " = " + i * num1 + "<br/></td></tr></table>");
                                    }

                    }   

</script>

</div>
    </section>
</body>
</html>

I've already attempted to use document.getElementByID('div1').innerHTML = i; However, this code did not work. I believe it may be a beginner's mistake, but I'm not entirely sure. Any insights would be greatly appreciated!

Thank you in advance!

Answer №1

If you want to have better control over your table, consider using a div as a placeholder for it, like this:

function practice(){
var num = prompt("Enter a number", "0");
var num1 = parseInt(num); 
var table = document.getElementById("tablebody");

for(var i= 1; i< 11; i++) {
var td = document.createElement("td"); //create TD
td.innerHTML = i + " x " + num1 + " = " + (i * num1);
var tr = document.createElement("tr");
tr.appendChild(td); //add TD to the TR
table.appendChild(tr); //add TR to the table
}
document.getElementById("placeholder").style.display = ""; 
} 
<section id="content">
<p>Want to learn the multiplication tables? Click on the practice button</p>
<button id="practice" name="practice" value="practice" onclick='practice()';>Practice Tables!   </button>
<div id="1"> <!-- Not sure why this div is here -->
</div>
<div id="placeholder" style="display:none;"> <!-- Placeholder area -->
<table border="1" id="tablebody"></table>
<div>
</section>

Remember to var the i in the loop to keep it scoped to the function. Using createElement may seem lengthy, but it's preferable for creating complex mark-up and easier to manage. It helps trace what's happening and can be broken into smaller functions.

Answer №2

Everything is functioning correctly here. ## UPDATED based on previous requests to have it displayed below the button

function oefenen() {
  var num = prompt("Enter a number", "0");
  var num1 = parseInt(num);

  for (i = 1; i < 11; i++) {
    document.getElementById('results').innerHTML+=("<tr><td>" + i + " x " + num1 + " = " + i * num1 + "<br/></td></tr>");
  }

}
<section id="content">
  
  <p>Do you want to learn the tables? Click the practice button</p>
  
  <button id="oefenen" name="oefenen" value="oefenen" onclick='oefenen()' ;>Practice Tables!</button>
  
  <table border="1" id=
"results">
    </table>
  
</section>

Answer №3

Here is a custom code to display the multiplication table for a specific number:

     <!doctype html>
<html>
<head>
    <title>Multiplication Table</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
   <section id="content">

  <p>Do you want to learn the multiplication tables? Click the practice button</p>

  <button id="practice" name="practice" value="practice" onclick='practice()' ;>Practice Tables!</button>
  <br />  <br />
  <div id="math">

  </div>

</section>
<script>
function practice() {
  var num = prompt("Enter a number", "0");
  var num1 = parseInt(num);

  for (i = 1; i < 11; i++) {
    document.getElementById('math').innerHTML+=(num1 + " x " + i + " = " + i * num1 + "<br/>");}

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

Answer №4

"When you use the document.write() method on an already loaded HTML document, it will overwrite all existing HTML elements" as mentioned by w3schools

In my opinion, utilizing innerHTML is a more suitable approach

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The protection ensured by employing an extensive hash in the query string for the recognition of a changing document

I am currently developing a small web application that creates exercise program printouts. The concept is simple - a user like a personal trainer can craft an exercise regimen and send it to their client via email using a unique link. http://www.myurl ...

Delete the element that was generated using jQuery

Is there a way to add and remove an overlay element using JavaScript? I am struggling to get JavaScript to remove an element that was created with JavaScript. Any suggestions? Check out this JS Fiddle example Here is the HTML code: <div id="backgroun ...

Two sets of buttons, however, one set is carrying out the incorrect function

I am trying to create two button sets that, when clicked, are supposed to angle the text below them at 45 degrees. However, I am facing an issue where both set 1 and set 2 only control the text linked to button 1. I need each button set to control their ...

Populate a PHP array with data retrieved using MySQL fetch operation

I am looking to extract the "till.code" values and store them in an array with incremental numeric indexing. The goal is to be able to print these values using "$array[$variable],$array[$variable]..etc". The variable should be a numerical number, 1, 2, ...

Enhancing text display and spacing in Safari versions 5 to 6, as well as Chrome

After creating an introductory animation using jquery, I noticed that it displays correctly on my machine in Firefox, Chrome, and Safari. However, when viewing it on the client's devices, the animation is not working properly. The client provided a s ...

The structure of the figure tag for HTML5 validation

Could you please confirm if the Figure tag is correctly used in the html structure? Regarding html5 validation, can I use this structure? <a href="#"> <figure> <img src="" class="img-responsive" alt=""> <figcaption> ...

Having trouble setting the select value with JavaScript in the Selenium web driver

I am working on a web page that includes a cascaded dropdown feature. The data in the second dropdown appears to be generated via ajax based on the selection made in the first dropdown. Here is the code for the first select option: <select class="form- ...

Encountering issues with loading a module in Aurelia

I've encountered a peculiar issue while attempting to load a module using Aurelia. The moment library was successfully loaded for date formatting, but when trying to load the numeral library in the same manner with npm install <module> --save, i ...

Turn a textfield on and off in real-time

Hey everyone, I've been working on making a textfield dynamic and I wanted to share my code with you: <input type="text" id="test1" value ="dynamic" onfocus="this.disabled=true" onblur="this.disabled=false"> <input type="text" id="test2 ...

Left-aligned arrow for Material UI select dropdown

Just starting out with material ui and I'm trying to grasp a few concepts. I have a basic select component but encountering two issues. Firstly, I'd like to move the arrow icon of the select to the left side instead of the right. Additionally, ...

In Angular components, data cannot be updated without refreshing the page when using setInterval()

Here's the Angular component I'm working with: export class UserListComponent implements OnInit, OnDestroy { private _subscriptions: Subscription; private _users: User[] = []; private _clickableUser: boolean = true; constructor( priv ...

Interacting Shadows with BufferGeometry in react-three-fiber

I've been working on my custom bufferGeometry in react-three-fiber, but I can't seem to get any shadows to show up. All the vertices, normals, and UVs are set correctly in my bufferGeometry, and I even tried adding indices to faces, but that just ...

Troubleshooting: React CSS Transition Fails to Trigger on Exit and Entry

This code is located inside my component file <CSSTransition classNames="method" in={radio === 'add-card'} exit={radio !== 'add-card'} timeout={500} unmountOnExit> < ...

I need help accessing data from a REST API and displaying it in a table

How can I call all the data in "md" and display it in a table? I've tried multiple values but none seem to work. Can someone guide me on how to use the "md" value to display in a table? <script src="https://ajax.googleapis.com/ajax/libs/jquery/ ...

Exploring the differences between server-side rendering and client-side rendering in Express using Pug

I find myself in a state of confusion when it comes to distinguishing between what is considered client-side and server-side. Currently, as I develop a website using Pug for my HTML pages without any external files being loaded into the client's brows ...

Utilizing ReactJS to dynamically display various content based on onclick event

Is it possible to dynamically display different content based on button clicks? I want to create a schedule where clicking on specific days like Monday will reveal exercises and timings only for that day. The same goes for Thursday and other days. You ca ...

The function you are trying to call is not callable. The type 'Promise<void>' does not have any call signatures. This issue is related to Mongodb and Nodejs

Currently, I am attempting to establish a connection between MongoDB and Node (ts). However, during the connection process, I encountered an error stating: "This expression is not callable. Type 'Promise<void>' has no call signatures" da ...

Oops! You can only have one parent element in JSX expressions

I'm working on creating a password input box, but I keep encountering an error when integrating it into my JS code. Here's the snippet of my code that includes TailwindCSS: function HomePage() { return ( <div> <p className=&q ...

The cascade option in TypeORM entities

In my project, I am working with two entities named Order and Address, which are connected through a @ManyToMany relationship. For the Address entity: @ManyToMany(() => Order, (order) => order.address, { cascade: true }) @JoinTable() order: Order; ...

What causes the variable assigned in the outer subscription's scope to change as the inner subscriptions change?

In my Angular 6 code snippet provided below, I am facing an issue: ngOnInit() { this.route.queryParams.subscribe((params: Params) => { const stuffId: string = params.stuffId; this.service.getState().subscribe((state) => { ...