0% found this document useful (0 votes)
8 views19 pages

JavaScript Basics in HTML Examples

Uploaded by

rubiakahelohei
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views19 pages

JavaScript Basics in HTML Examples

Uploaded by

rubiakahelohei
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

DIGITAL REGENESYS JAVA SCRIPT PRACTICALS

Basic HTML with JavaScript Example:


<!DOCTYPE html>
<html lang="en">
<head>
<title>JavaScript in HTML Example</title>
</head>
<body>
<h1>Hello, World!</h1>
<p>Click the button to see a message.</p>

<!-- Button that triggers JavaScript function -->


<button onclick="showMessage()">Click Me</button>

<!-- JavaScript can be embedded within the HTML file -->


<script>
// This is a JavaScript function
function showMessage()
{
alert('Hello! This is a message from JavaScript.');
}
</script>
</body>
</html>

OR
<!DOCTYPE html>
<html lang="en">
<head>
<title>JavaScript in HTML Example</title>
<script>
// This is a JavaScript function
function showMessage()
{
alert('Hello! This is a message from JavaScript.');
}
</script>
</head>
<body>
<h1>Hello, World!</h1>
<p>Click the button to see a message.</p>

<!-- Button that triggers JavaScript function -->


<button onclick="showMessage()">Click Me</button>

<!-- JavaScript can be embedded within the HTML file -->


</body>
</html>

[Link] Ahmad Khan 1


DIGITAL REGENESYS JAVA SCRIPT PRACTICALS

Explanation:
1. HTML Structure: The basic structure of the HTML document is defined using the <!DOCTYPE html> declaration,
followed by the <html>, <head>, and <body> tags.
2. JavaScript in the <script> Tag: JavaScript code is placed inside the <script> tag. In this example, the function
showMessage() is defined within this tag.
3. Event Handling: The onclick attribute in the <button> element is used to trigger the showMessage() function
when the button is clicked.
4. Alert Function: The alert() method is used to display a simple message in a dialog box.

External JavaScript File (Optional):


You can also include JavaScript from an external file. Here's how you can link it:
1. External JavaScript File: Create a file named [Link] with the following content:
function showMessage()
{
alert('Hello! This is a message from an external JavaScript file.');
}

2. HTML Linking the External JavaScript:


<!DOCTYPE html>
<html lang="en">
<head>
<title>JavaScript in HTML Example</title>
<!-- Link to external JavaScript file -->
<script src="[Link]"></script>
</head>
<body>
<h1>Hello, World!</h1>
<p>Click the button to see a message.</p>
<button onclick="showMessage()">Click Me</button>
</body>
</html>

1. Hello World in HTML


<!DOCTYPE html>
<html lang="en">
<head>
<title>Hello World Example</title>
</head>
<body bgcolor=#58d68d>
<h1>Hello World Example</h1>
<p id="message"></p>

<script>
[Link]("message").innerHTML = "Hello, World!";
</script>
</body>
</html>

[Link] Ahmad Khan 2


DIGITAL REGENESYS JAVA SCRIPT PRACTICALS

Explanation:
• The [Link]("message").innerHTML changes the content of the paragraph with the ID
message.
• This program displays "Hello, World!" in the paragraph tag (<p>), demonstrating how to modify HTML
content using JavaScript.

2. Basic Arithmetic in HTML


<!DOCTYPE html>
<html lang="en">
<head>
<title>Arithmetic Example</title>
</head>
<body>
<h1>Basic Arithmetic</h1>
<p id="result"></p>

<script>
let a = 10;
let b = 5;
let sum = a + b;
[Link]("result").innerHTML = "The sum of " + a + " and " + b + " is " + sum;
</script>
</body>
</html>

3. Arithmetic Operations in HTML


<!DOCTYPE html>
<html>
<head>
<title>Arithmetic Operations</title>
</head>
<body bgcolor= #d7bde2>
<h1>Arithmetic Operations</h1>

<label for="num1">Enter the first number:</label><br/><br/>


<input type="number" id="num1"><br/><br/>

<label for="num2">Enter the second number:</label><br/><br/>


<input type="number" id="num2"><br/><br/>

<button onclick="performOperations()">Perform Operations</button>

<div id="results"></div>

<script>

[Link] Ahmad Khan 3


DIGITAL REGENESYS JAVA SCRIPT PRACTICALS

function performOperations()
{
var num1 = parseFloat([Link]('num1').value);
var num2 = parseFloat([Link]('num2').value);

var addition = num1 + num2;


var subtraction = num1 - num2;
var multiplication = num1 * num2;
var division = num1 / num2;
var modulo = num1 % num2;

var results = [Link]('results');


[Link] = "<h3>Arithmetic Operations Results:</h3>" +
"<p>Addition: " + num1 + " + " + num2 + " = " + addition + "</p>" +
"<p>Subtraction: " + num1 + " - " + num2 + " = " + subtraction + "</p>" +
"<p>Multiplication: " + num1 + " * " + num2 + " = " + multiplication + "</p>" +
"<p>Division: " + num1 + " / " + num2 + " = " + division + "</p>" +
"<p>Modulo: " + num1 + " % " + num2 + " = " + modulo + "</p>";
}
</script>
</body>
</html>

Explanation:

HTML Structure:
<!DOCTYPE html>
<html>
<head>
<title>Arithmetic Operations</title>
</head>
<body bgcolor=" #d7bde2 ">
<h1>Arithmetic Operations</h1>

• The code starts with the <!DOCTYPE html> declaration, which defines the document as an HTML5 document.
• The <head> section includes a <title> tag that sets the title of the webpage as "Arithmetic Operations."
• The <body> tag has a bgcolor attribute set to " #d7bde2 ", which changes the background color of the page
to cyan.
• The <h1> tag is used to create a heading that reads "Arithmetic Operations."

Input Fields for Numbers:


<label for="num1">Enter the first number:</label><br/><br/>
<input type="number" id="num1"><br/><br/>

<label for="num2">Enter the second number:</label><br/><br/>


<input type="number" id="num2"><br/><br/>

• Two labels and input fields are provided for the user to enter the first and second numbers.
• The <label> tag associates’ text with the corresponding input field.
• The <input> tags have type="number", which ensures that only numeric input is allowed.

[Link] Ahmad Khan 4


DIGITAL REGENESYS JAVA SCRIPT PRACTICALS

• Each input field is assigned a unique id (num1 and num2) so that they can be referenced in the JavaScript
code.
• <br/> tags are used to add line breaks for spacing between the elements.

Button to Trigger the Calculation:


<button onclick="performOperations()">Perform Operations</button>

• A button is created with the text "Perform Operations."


• The onclick attribute is set to call the performOperations() function when the button is clicked, triggering the
arithmetic calculations.

Display Area for Results:


<div id="results"></div>

• An empty <div> with the id="results" is provided to display the results of the arithmetic operations. The
results will be dynamically inserted here by the JavaScript code.

JavaScript Code:
<script>
function performOperations()
{
var num1 = parseFloat([Link]('num1').value);
var num2 = parseFloat([Link]('num2').value);

• The JavaScript code is enclosed within the <script> tags.


• The performOperations() function is defined to carry out the arithmetic operations.
• [Link]('num1').value and [Link]('num2').value retrieve the values
entered in the input fields.
• parseFloat() is used to convert the input values (which are initially strings) into floating-point numbers for
accurate calculations.

Arithmetic Operations:
var addition = num1 + num2;
var subtraction = num1 - num2;
var multiplication = num1 * num2;
var division = num1 / num2;
var modulo = num1 % num2;

• The arithmetic operations are performed and stored in variables:


o addition stores the sum of num1 and num2.
o subtraction stores the difference between num1 and num2.
o multiplication stores the product of num1 and num2.
o division stores the quotient of num1 divided by num2.
o modulo stores the remainder when num1 is divided by num2.

Displaying the Results:


var results = [Link]('results');
[Link] = "<h3>Arithmetic Operations Results:</h3>" +
"<p>Addition: " + num1 + " + " + num2 + " = " + addition + "</p>" +
"<p>Subtraction: " + num1 + " - " + num2 + " = " + subtraction + "</p>" +
"<p>Multiplication: " + num1 + " * " + num2 + " = " + multiplication + "</p>" +

[Link] Ahmad Khan 5


DIGITAL REGENESYS JAVA SCRIPT PRACTICALS

"<p>Division: " + num1 + " / " + num2 + " = " + division + "</p>" +
"<p>Modulo: " + num1 + " % " + num2 + " = " + modulo + "</p>";
}
</script>

• The results variable is assigned the <div> element with the id="results".
• The innerHTML property of the results div is set to a string that includes the HTML for displaying the results
of the arithmetic operations.
• Each operation's result is displayed using a series of <p> tags, with the operation details and results included.
• The + operator is used to concatenate strings and variables.

Summary:

• User Interaction: The user inputs two numbers and clicks the "Perform Operations" button.
• Functionality: The JavaScript function performOperations() retrieves the input values, performs the
arithmetic operations, and displays the results within the webpage.
• Display: The results are shown in a formatted and color-coded section below the input fields.

4. Area and Perimeter of a Circle


<!DOCTYPE html>
<html>
<head>
<title>Circle Area and Perimeter</title>
</head>
<body bgcolor="#f9e79f">
<h1>Circle Area and Perimeter</h1>

<label for="radius">Enter the radius of the circle:</label><br/><br/>


<input type="number" id="radius"><br/><br/>

<button onclick="calculateCircle()">Calculate</button>

<div id="circleResults"></div>

<script>
function calculateCircle() {
var radius = parseFloat([Link]('radius').value);

var area = [Link] * radius * radius;


var perimeter = 2 * [Link] * radius;

var results = [Link]('circleResults');


[Link] = "<h3>Circle Calculations:</h3>" +
"<p>Area: π * " + radius + "² = " + [Link](2) + "</p>" +
"<p>Perimeter (Circumference): 2 * π * " + radius + " = " + [Link](2) + "</p>";
}
</script>
</body>
</html>

[Link] Ahmad Khan 6


DIGITAL REGENESYS JAVA SCRIPT PRACTICALS

Explanation:
• Input: The user inputs the length and width of the rectangle.
• Output: The area and perimeter of the rectangle are calculated and displayed.

General Structure:
• HTML Structure: Both programs have a similar structure with <label> and <input> elements for user inputs, a
<button> to trigger the calculation, and a <div> to display the results.
• JavaScript: The functions calculateCircle() and calculateRectangle() handle the respective calculations. The
results are dynamically displayed in the corresponding <div> elements using innerHTML. The calculations are
formatted and presented clearly to the user.

These examples should provide a good foundation for creating similar programs that involve basic arithmetic
calculations.

5. Area of a Triangle when Base and Height is known:


<!DOCTYPE html>
<html>
<head>
<title>Triangle Area Calculator</title>
</head>
<body bgcolor="#f0b27a">
<h1>Calculate the Area of a Triangle</h1>

<label for="base">Enter the base of the triangle:</label><br/><br/>


<input type="number" id="base"><br/><br/>

<label for="height">Enter the height of the triangle:</label><br/><br/>


<input type="number" id="height"><br/><br/>

<button onclick="calculateArea()">Calculate Area</button>

<div id="areaResult"></div>

<script>
function calculateArea() {
// Get values from the input fields
const baseValue = parseFloat([Link]('base').value);
const heightValue = parseFloat([Link]('height').value);

// Calculate the area of the triangle


const areaValue = (baseValue * heightValue) / 2;

// Display the result on the page


const resultDiv = [Link]('areaResult');
[Link] = `<h3>The area of the triangle is ${[Link](2)}</h3>`;
}
</script>
</body>
</html>

[Link] Ahmad Khan 7


DIGITAL REGENESYS JAVA SCRIPT PRACTICALS

Explanation:
1. HTML Structure:
o The <label> and <input> tags are used to create fields where the user can enter the base and height of
the triangle.
o The type="number" attribute in the <input> tags ensures that the input is numeric.

2. Button:
o The <button> tag is used to create a "Calculate Area" button.
o When the button is clicked, it triggers the calculateArea() function.

3. JavaScript Function:
o The calculateArea() function retrieves the values entered by the user for the base and height using
[Link]().value.
o It calculates the area of the triangle using the formula (base * height) / 2.
o The result is displayed within the areaResult <div> on the page.
o The .toFixed(2) method is used to format the area to two decimal places for better readability.

4. Display:
o The area of the triangle is displayed directly on the webpage under the input fields after the user clicks
the "Calculate Area" button.

This structure provides a user-friendly interface for calculating the area of a triangle, with the result displayed
immediately on the page.

6. Area of a Triangle when all sides are known:

If you know all the sides of a triangle, you can find the area using Herons' formula. If a, b and c are the three sides
of a triangle, then

s = (a+b+c)/2
area = √(s(s-a)*(s-b)*(s-c))

<!DOCTYPE html>
<html>
<head>
<title>Triangle Area Calculator (Heron's Formula)</title>
</head>
<body bgcolor="#d7bde2">
<h1>Calculate the Area of a Triangle using Heron's Formula</h1>

<label for="side1">Enter side 1:</label><br/><br/>


<input type="number" id="side1"><br/><br/>

<label for="side2">Enter side 2:</label><br/><br/>


<input type="number" id="side2"><br/><br/>

<label for="side3">Enter side 3:</label><br/><br/>


<input type="number" id="side3"><br/><br/>

<button onclick="calculateTriangleArea()">Calculate Area</button>

[Link] Ahmad Khan 8


DIGITAL REGENESYS JAVA SCRIPT PRACTICALS

<div id="areaResult"></div>

<script>
function calculateTriangleArea() {
// Get the values of the three sides from the input fields
const side1 = parseFloat([Link]('side1').value);
const side2 = parseFloat([Link]('side2').value);
const side3 = parseFloat([Link]('side3').value);

// Calculate the semi-perimeter


const s = (side1 + side2 + side3) / 2;

// Calculate the area using Heron's formula


const areaValue = [Link](
s * (s - side1) * (s - side2) * (s - side3)
);

// Display the result on the page


const resultDiv = [Link]('areaResult');
[Link] = `<h3>The area of the triangle is ${[Link](2)}</h3>`;
}
</script>
</body>
</html>

7. Check if a Number is Positive, Negative, or Zero:


<!DOCTYPE html>
<html lang="en">
<head>
<title>Check Number: Positive, Negative, or Zero</title>
</head>
<body>
<h1>Check if a Number is Positive, Negative, or Zero</h1>

<button onclick="checkNumber()">Enter a Number</button>

<p id="result"></p>

<script>
function checkNumber() {
// Program that checks if the number is positive, negative or zero
// Input from the user
const number = parseInt(prompt("Enter a number: "));

// Variable to hold the result message


let message;

[Link] Ahmad Khan 9


DIGITAL REGENESYS JAVA SCRIPT PRACTICALS

// Check if number is greater than 0


if (number > 0) {
message = "The number is positive";
}
// Check if number is 0
else if (number === 0) {
message = "The number is zero";
}
// If number is less than 0
else {
message = "The number is negative";
}
// Display the result in the paragraph with id "result"
[Link]("result").innerHTML = message;
}
</script>
</body>
</html>

Explanation:
This program is an interactive web application that allows the user to check whether a number is positive,
negative, or zero. Here's a detailed explanation of how it works:

1. DOCTYPE Declaration:
<!DOCTYPE html>: This tells the browser that the document is an HTML5 document.

2. Language and Head Section:


o <html lang="en">: This indicates that the language of the document is English.
o <head>: Contains metadata and the title of the document.
o <title>: Sets the title of the webpage that appears in the browser tab as "Check Number: Positive,
Negative, or Zero".

3. Body Section:
o <body>: Contains the visible content of the webpage.
o <h1>: Displays the main heading of the page, "Check if a Number is Positive, Negative, or Zero".
o <button>: Creates a button labeled "Enter a Number". When this button is clicked, it triggers the
checkNumber() function.
o <p id="result"></p>: This paragraph will be used to display the result of the check (whether the number
is positive, negative, or zero). Initially, it is empty.

JavaScript Function:
1. Function Definition:
The <script> tag encloses the JavaScript code that adds interactivity to the webpage.

2. checkNumber() Function:
Prompt for Input:
▪ const number = parseInt(prompt("Enter a number: "));: This line prompts the user to enter a number. The
prompt() function opens a dialog box asking the user to input a number. The parseInt() function converts
the input from a string to an integer.

[Link] Ahmad Khan 10


DIGITAL REGENESYS JAVA SCRIPT PRACTICALS

Result Message Variable:


▪ let message;: Declares a variable named message that will hold the result message ("The number is
positive", "The number is zero", or "The number is negative").

Conditional Logic:
▪ The if...else if...else structure checks the value of the input number and assigns an appropriate message
to the message variable.
▪ if (number > 0): If the number is greater than 0, the message is "The number is positive".
▪ else if (number === 0): If the number is equal to 0, the message is "The number is zero". The ===
operator is used to check for strict equality.
▪ else: If the number is less than 0, the message is "The number is negative".

Displaying the Result:


▪ [Link]("result").innerHTML = message;: This line displays the result message in the
<p> element with the id="result". The innerHTML property is used to insert the content (the result
message) into the paragraph.

How the Program Works:


1. User Interaction:
The user clicks the "Enter a Number" button, which calls the checkNumber() function.

2. Input and Processing:


o A dialog box appears, asking the user to enter a number.
o The entered number is processed by the checkNumber() function, which checks whether the number is
positive, negative, or zero.

3. Output:
o The program displays the result below the button in the <p> element with the id="result". The result will
be one of three possible messages: "The number is positive", "The number is zero", or "The number is
negative".

8. Check if a Number is Positive, Negative, or Zero_<style> tag:


<!DOCTYPE html>
<html lang="en">
<head>
<title>Check Number: Positive, Negative, or Zero</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
}
label {
font-size: 18px;
margin-right: 10px;
}
input[type="text"] {
padding: 5px;
font-size: 16px;
}

[Link] Ahmad Khan 11


DIGITAL REGENESYS JAVA SCRIPT PRACTICALS

button {
padding: 5px 10px;
font-size: 16px;
margin-left: 10px;
cursor: pointer;
}
#result {
margin-top: 20px;
font-weight: bold;
font-size: 20px;
}
.positive {
color: green;
}
.negative {
color: red;
}
.zero {
color: blue;
}
</style>
</head>
<body bgcolor=cyan>
<h1>Check if a Number is Positive, Negative, or Zero</h1>

<label for="numberInput">Enter a number:</label>


<input type="text" id="numberInput" placeholder="Type a number">
<button onclick="checkNumber()">Check</button>

<p id="result"></p>

<script>
function checkNumber() {
// Get the value from the textbox
const number = parseInt([Link]("numberInput").value);

// Variable to hold the result message


let message;

// Check if number is greater than 0


if (number > 0) {
message = "The number is positive";
[Link]("result").className = "positive";
}
// Check if number is 0
else if (number === 0) {
message = "The number is zero";
[Link]("result").className = "zero";
}
// If number is less than 0
else if (number < 0) {

[Link] Ahmad Khan 12


DIGITAL REGENESYS JAVA SCRIPT PRACTICALS

message = "The number is negative";


[Link]("result").className = "negative";
} else {
message = "Please enter a valid number!";
[Link]("result").className = "";
}

// Display the result in the paragraph with id "result"


[Link]("result").innerHTML = message;
}
</script>
</body>
</html>

9. Calculate the Factorial of a Number:


<!DOCTYPE html>
<html>
<head>
<title>Factorial Calculator</title>
</head>
<body bgcolor=" #d1f2eb ">
<h1>Calculate the Factorial of a Number</h1>

<label for="number">Enter a positive integer:</label><br/><br/>


<input type="number" id="number"><br/><br/>

<button onclick="calculateFactorial()">Calculate Factorial</button>

<div id="factorialResult"></div>

<script>
function calculateFactorial() {
// Get the input value
const number = parseInt([Link]('number').value);

// Initialize the message variable


let message;

// Check if the number is negative


if (number < 0) {
message = 'Error! Factorial for negative number does not exist.';
}
// Check if the number is 0
else if (number === 0) {
message = `The factorial of ${number} is 1.`;
}

[Link] Ahmad Khan 13


DIGITAL REGENESYS JAVA SCRIPT PRACTICALS

// If the number is positive


else {
let fact = 1;
for (let i = 1; i <= number; i++) {
fact *= i;
}
message = `The factorial of ${number} is ${fact}.`;
}

// Display the result


[Link]('factorialResult').innerHTML = `<h3>${message}</h3>`;
}
</script>
</body>
</html>

Explanation:
1. HTML Structure:
• Input Field:
The user can enter a positive integer in the input field (<input type="number" id="number">).
• Button:
The "Calculate Factorial" button triggers the calculateFactorial() function when clicked.
• Result Display:
The result will be displayed in the <div id="factorialResult"></div> element on the page.

2. JavaScript Function:
• Input Retrieval:
The number is retrieved from the input field using [Link]('number').value and converted
to an integer using parseInt().
• Conditional Logic:
▪ Negative Number Check:
If the entered number is negative, an error message is displayed ('Error! Factorial for negative
number does not exist.').
▪ Zero Check:
If the number is 0, the factorial is 1 ('The factorial of 0 is 1.').
▪ Positive Number:
o For positive numbers, a for loop calculates the factorial by multiplying numbers from 1 to the
entered number.
o The calculated factorial is displayed in the result message.
• Displaying the Result:
The result is displayed on the webpage in the factorialResult <div> using innerHTML.

How It Works:
1. User Interaction:
The user enters a positive integer and clicks the "Calculate Factorial" button.

2. Calculation:
The JavaScript function processes the input to check if it’s negative, zero, or positive, and then calculates the
factorial accordingly.

[Link] Ahmad Khan 14


DIGITAL REGENESYS JAVA SCRIPT PRACTICALS

3. Output:
The result (factorial of the entered number) or an error message is displayed on the webpage.

[Link] Calculator:
<!DOCTYPE html>
<html>
<head>
<title>Simple Calculator</title>
</head>
<body bgcolor="#d7bde2">
<h1>Simple Calculator</h1>

<label for="number1">Enter first number:</label><br/><br/>


<input type="number" id="number1"><br/><br/>

<label for="operator">Choose an operator ( +, -, *, / ):</label><br/><br/>


<input type="text" id="operator"><br/><br/>

<label for="number2">Enter second number:</label><br/><br/>


<input type="number" id="number2"><br/><br/>

<button onclick="calculate()">Calculate</button>

<div id="calculatorResult"></div>

<script>
function calculate() {
// Get the values from the input fields
const number1 = parseFloat([Link]('number1').value);
const operator = [Link]('operator').value;
const number2 = parseFloat([Link]('number2').value);

let result;

// Perform the calculation based on the operator


if (operator == '+') {
result = number1 + number2;
} else if (operator == '-') {
result = number1 - number2;
} else if (operator == '*') {
result = number1 * number2;
} else if (operator == '/') {
result = number1 / number2;
} else {
result = 'Invalid operator';
}

[Link] Ahmad Khan 15


DIGITAL REGENESYS JAVA SCRIPT PRACTICALS

// Display the result


const resultDiv = [Link]('calculatorResult');
[Link] = `<h3>${number1} ${operator} ${number2} = ${result}</h3>`;
}
</script>
</body>
</html>

Explanation:
1. HTML Structure:
Input Fields:
Three input fields are provided:
1. For the first number (<input type="number" id="number1">).
2. For the operator (<input type="text" id="operator">).
3. For the second number (<input type="number" id="number2">).

Button:
A "Calculate" button triggers the calculate() function when clicked.

Result Display:
The result of the calculation is displayed in the <div id="calculatorResult"></div> element on the page.

2. JavaScript Function:
Input Retrieval:
The numbers and the operator are retrieved from their respective input fields.

Conditional Logic:
The program checks the value of the operator to determine which arithmetic operation to perform:
1. + for addition.
2. - for subtraction.
3. * for multiplication.
4. / for division.

If the operator is not one of the four valid options, the program returns "Invalid operator".

Displaying the Result:


The result is displayed on the webpage in the calculatorResult <div> using innerHTML.

3. How It Works:
▪ The user inputs two numbers and an operator.
▪ The "Calculate" button triggers the calculation based on the operator provided.
▪ The result of the calculation is displayed on the webpage.

[Link] Table Up to 10:


<!DOCTYPE html>
<html>
<head>
<title>Multiplication Table Generator</title>
</head>

[Link] Ahmad Khan 16


DIGITAL REGENESYS JAVA SCRIPT PRACTICALS

<body bgcolor="#d4efdf">
<h1>Multiplication Table Generator</h1>

<label for="number">Enter an integer:</label><br/><br/>


<input type="number" id="number"><br/><br/>

<button onclick="generateTable()">Generate Table</button>

<div id="multiplicationTable"></div>

<script>
function generateTable() {
// Get the input value
const number = parseInt([Link]('number').value);

// Variable to store the multiplication table


let table = `<h3>Multiplication Table for ${number}</h3>`;

// Generate the multiplication table


for(let i = 1; i <= 10; i++) {
const result = i * number;
table += `<p>${number} * ${i} = ${result}</p>`;
}

// Display the multiplication table


[Link]('multiplicationTable').innerHTML = table;
}
</script>
</body>
</html>

Explanation:
1. HTML Structure:
o Input Field:
The user can input an integer in the input field (<input type="number" id="number">).
o Button:
The "Generate Table" button triggers the generateTable() function when clicked.
o Result Display:
The multiplication table will be displayed in the <div id="multiplicationTable"></div> element on the
page.

2. JavaScript Function:
o Input Retrieval:
The number is retrieved from the input field using [Link]('number').value and
converted to an integer using parseInt().
o Generating the Multiplication Table:
▪ A for loop iterates from 1 to 10, multiplying the input number by the loop variable i.
▪ The result of each multiplication is appended to the table string variable, which will store the entire
multiplication table.

[Link] Ahmad Khan 17


DIGITAL REGENESYS JAVA SCRIPT PRACTICALS

o Displaying the Result:


The generated multiplication table is displayed on the webpage in the multiplicationTable <div> using
innerHTML.

3. How It Works:
o The user inputs an integer and clicks the "Generate Table" button.
o The generateTable() function creates the multiplication table for that number.
o The table is displayed on the webpage.

This program allows users to generate a multiplication table for any integer they enter, directly on the webpage.

[Link] Table Up to a Range:


<!DOCTYPE html>
<html>
<head>
<title>Multiplication Table Generator</title>
</head>
<body bgcolor="#d7bde2">
<h1>Multiplication Table Generator</h1>

<label for="number">Enter an integer:</label><br/><br/>


<input type="number" id="number"><br/><br/>

<label for="range">Enter a range:</label><br/><br/>


<input type="number" id="range"><br/><br/>

<button onclick="generateTable()">Generate Table</button>

<div id="multiplicationTable"></div>

<script>
function generateTable() {
// Get the input values
const number = parseInt([Link]('number').value);
const range = parseInt([Link]('range').value);

// Variable to store the multiplication table


let table = `<h3>Multiplication Table for ${number} up to ${range}</h3>`;

// Generate the multiplication table up to the specified range


for(let i = 1; i <= range; i++) {
const result = i * number;
table += `<p>${number} * ${i} = ${result}</p>`;
}

// Display the multiplication table


[Link]('multiplicationTable').innerHTML = table;
}
</script>

[Link] Ahmad Khan 18


DIGITAL REGENESYS JAVA SCRIPT PRACTICALS

</body>
</html>

Explanation:
1. HTML Structure:
o Input Fields:
▪ The user can input an integer in the input field (<input type="number" id="number">).
▪ The user can also input a range in the second input field (<input type="number" id="range">).
o Button:
▪ The "Generate Table" button triggers the generateTable() function when clicked.
o Result Display:
▪ The multiplication table will be displayed in the <div id="multiplicationTable"></div> element on the
page.

2. JavaScript Function:
o Input Retrieval:
▪ The number and the range are retrieved from their respective input fields using
[Link]('number').value and [Link]('range').value, and
converted to integers using parseInt().
o Generating the Multiplication Table:
▪ A for loop iterates from 1 to the specified range, multiplying the input number by the loop variable i.
▪ The result of each multiplication is appended to the table string variable, which will store the entire
multiplication table.
o Displaying the Result:
▪ The generated multiplication table is displayed on the webpage in the multiplicationTable <div>
using innerHTML.
3. How It Works:
o The user inputs an integer and a range, then clicks the "Generate Table" button.
o The generateTable() function creates the multiplication table for that number up to the specified range.
o The table is displayed on the webpage.

This program allows users to generate a multiplication table for any integer they enter, up to a specified range,
directly on the webpage.

[Link] Ahmad Khan 19

You might also like