JavaScript: Dynamically generate tables and calculate column sums
This document is intended to guide beginners to dynamically generate HTML tables using JavaScript, calculate the sum of each column, and finally add the sum to the bottom of the table as a new row. Through this article, you will learn how to manipulate DOM elements with JavaScript, create tables, and perform simple numerical calculations.
Dynamically generate tables and calculate column sums
In web development, it is often necessary to dynamically generate tables and perform some calculations. This tutorial demonstrates how to create a table using JavaScript that calculates the sum of squares of the number entered by the user, and displays the results in the table. Finally, we will also calculate the sum of each column and add it to the bottom of the table.
1. HTML structure
First, we need to create an input box, a button, and a div element in HTML that displays the results:
<input id="broj" type="text"> <button onclick="tablica()">Generate table</button> <div id="rezultat"></div>
2. JavaScript code
Next, we will write JavaScript code to implement table generation and calculation.
function tablica() { var sum1 = 0, sum2 = 0, sum3 = 0; // Initialize the sum of columns var nr = document.getElementById("broj").value; // Get the number entered by the user// Input verification if (nr <tr> <th>N</th> <th>N²</th> <th>N!</th> </tr>"; var faktorijela = 1; // Initialize factorials// Loop to generate table rows for (var i = 1; i <td>" val1 "</td><td>" val2 "</td><td>" val3 "</td>"; // Accumulated column sum1 = sum1 val1; sum2 = sum2 val2; sum3 = sum3 val3; } // Add sum line rez = rez "<tr> <td>" sum1 "</td> <td>" sum2 "</td> <td>" sum3 "</td> </tr>"; rez = rez ""; // Show the table on the page var rezTablica = document.getElementById("rezultat"); rezTablica.innerHTML = rez; }
Code explanation:
- Initialize variables:
- sum1, sum2, sum3: is used to store the sum of each column, with an initial value of 0.
- nr: Gets the number entered by the user in the input box.
- rez: Used to build HTML table strings.
- faktorijela: is used to calculate factorial, with an initial value of 1.
- Input Verification: Check whether the user input is less than 2. If it is less than 2, an error message is displayed and the function execution ends.
- Create table header: Use HTML string to create the header of the table, including three columns "N", "N²", "N!".
- Loop to generate table rows:
- Use the for loop to iterate from 1 to the number nr entered by the user.
- In each iteration, the square (i * i) and factorial (faktorijela = faktorijela * i) of the current number are calculated.
- Use HTML string to create a row of the table, containing the current number, squares, and factorials.
- Add this line to the rez string.
- Accumulate the three values of the current row into sum1, sum2, and sum3 respectively.
- Add sum row: After the loop is finished, create the last row of the table using an HTML string, containing the sum of each column.
- Show table: Assign the complete HTML table string to the innerHTML property of the rezultat div to display the table on the page.
3. Operation results
When the user enters a number (for example, 5) in the input box and clicks the "Generate Table" button, the page will display a table with 5 rows of data, and a row will display the sum of each column at the bottom of the table.
4. Things to note
- Data type: Make sure that the user is entering a number. You can use the parseInt() or parseFloat() functions to convert the value in the input box into a number.
- Error handling: More error handling mechanisms can be added, such as checking whether the user has entered non-numeric characters.
- Style beautification: You can use CSS to beautify the style of a table.
- Code reuse: The logic that generates the table can be encapsulated into an independent function, which is convenient for calling in other places.
5. Summary
With this tutorial, you learned how to dynamically generate HTML tables using JavaScript and calculate the sum of each column. This is just a simple example that you can expand and modify according to actual needs. Hope this tutorial is helpful to you!
The above is the detailed content of JavaScript: Dynamically generate tables and calculate column sums. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

To create an HTML unordered list, you need to use a tag to define a list container. Each list item is wrapped with a tag, and the browser will automatically add bullets; 1. Create a list with a tag; 2. Each list item is defined with a tag; 3. The browser automatically generates default dot symbols; 4. Sublists can be implemented through nesting; 5. Use the list-style-type attribute of CSS to modify the symbol style, such as disc, circle, square, or none; use these tags correctly to generate a standard unordered list.

Using tags is the easiest and recommended method. The syntax is suitable for modern browsers to embed PDF directly; 2. Using tags can provide better control and backup content support, syntax is, and provides download links in tags as backup solutions when they are not supported; 3. It can be embedded through Google DocsViewer, but it is not recommended to use widely due to privacy and performance issues; 4. In order to improve the user experience, appropriate heights should be set, responsive sizes (such as height: 80vh) and PDF download links should be provided so that users can download and view them themselves.

To add an icon to the website title bar, you need to link a favicon file in part of the HTML. The specific steps are as follows: 1. Prepare a 16x16 or 32x32 pixel icon file. It is recommended to use favicon.ico to name it and place it in the website root directory, or use modern formats such as PNG and SVG; 2. Add link tags to HTML, such as PNG or SVG formats, adjust the type attribute accordingly; 3. Optionally add high-resolution icons for mobile devices, such as AppleTouchIcon, and specify different sizes through the sizes attribute; 4. Follow best practices, place the icon in the root directory to ensure automatic detection, clear the browser cache after update, and check the correctness of the file path.

Choosing the right HTMLinput type can improve data accuracy, enhance user experience, and improve usability. 1. Select the corresponding input types according to the data type, such as text, email, tel, number and date, which can automatically checksum and adapt to the keyboard; 2. Use HTML5 to add new types such as url, color, range and search, which can provide a more intuitive interaction method; 3. Use placeholder and required attributes to improve the efficiency and accuracy of form filling, but it should be noted that placeholder cannot replace label.

Usetheelementwithinatagtocreateasemanticsearchfield.2.Includeaforaccessibility,settheform'sactionandmethod="get"attributestosenddatatoasearchendpointwithashareableURL.3.Addname="q"todefinethequeryparameter,useplaceholdertoguideuse

First, check whether the src attribute path is correct, and ensure that the relative or absolute path matches the HTML file location; 2. Verify whether the file name and extension are spelled correctly and case-sensitive; 3. Confirm that the image file actually exists in the specified directory; 4. Use appropriate alt attributes and ensure that the image format is .jpg, .png, .gif or .webp widely supported by the browser; 5. Troubleshoot browser cache issues, try to force refresh or directly access the image URL; 6. Check server permission settings to ensure that the file can be read and not blocked; 7. Verify that the img tag syntax is correct, including the correct quotes and attribute order, and finally troubleshoot 404 errors or syntax problems through the browser developer tool to ensure that the image is displayed normally.

Using HTML tags can improve the accessibility and clarity of content; 1. Mark abbreviations or acronyms with abbreviations; 2. Add title attributes to unusual abbreviations to provide a complete explanation; 3. Use when the document first appears, avoiding duplicate annotations; 4. You can customize the style through CSS, and the default browser usually displays dotted underscores; 5. It helps screen reader users understand terms and enhance user experience.

Using FontAwesome can quickly add icons by introducing CDN and adding icon classes to buttons, such as Like; 2. Using labels to embed custom icons in buttons, the correct path and size must be specified; 3. Embed SVG code directly to achieve high-resolution icons and keep them consistent with the text color; 4. Spacing should be added through CSS and aria-label should be added to the icon buttons to improve accessibility; in summary, FontAwesome is most suitable for standard icons, pictures are suitable for custom designs, while SVG provides the best scaling and control, and methods should be selected according to project needs. FontAwesome is usually recommended.
