0% found this document useful (0 votes)
23 views22 pages

FSD - Experiment - IX - For II-II-CSE

The document outlines a JavaScript application that allows users to perform various mathematical and string operations, including calculating the factorial of a number, generating the Fibonacci series, finding prime numbers, and checking if a string is a palindrome. Each operation is triggered by a button click, and results are displayed dynamically on the webpage. The HTML structure includes an input field and buttons for each operation, with corresponding JavaScript functions to handle the calculations and display results.

Uploaded by

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

FSD - Experiment - IX - For II-II-CSE

The document outlines a JavaScript application that allows users to perform various mathematical and string operations, including calculating the factorial of a number, generating the Fibonacci series, finding prime numbers, and checking if a string is a palindrome. Each operation is triggered by a button click, and results are displayed dynamically on the webpage. The HTML structure includes an input field and buttons for each operation, with corresponding JavaScript functions to handle the calculations and display results.

Uploaded by

DEVIKA G
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 22

9.

JavaScript Functions and Events


a. Design a appropriate function should be called to display
Factorial of that number
Desription:
To design a function in JavaScript that calculates the factorial of a number and displays the result, you
can create an event-driven approach, such as using a button click to trigger the factorial calculation.

1. HTML: The input field allows the user to enter a number, and the button triggers the factorial
calculation when clicked.
2. JavaScript:
o The calculateFactorial() function calculates the factorial of a given number.
o An event listener is added to the button, which triggers the calculation when clicked.
o The user input is validated to ensure it's a valid non-negative integer, and the result is
displayed in the paragraph (<p id="result"></p>).

1. The user enters a number into the input field.


2. When the "Calculate Factorial" button is clicked, the calculateFactorial() function is called.
3. The factorial of the entered number is calculated, and the result is displayed below the button.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Factorial Calculator</title>
</head>
<body>
<h1>Factorial Calculator</h1>
<label for="numberInput">Enter a number: </label>
<input type="number" id="numberInput" min="0">
<button id="calculateBtn">Calculate Factorial</button>

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

<script src="script.js"></script>
</body>
</html>
************************************************************
// Function to calculate the factorial of a number
function calculateFactorial(num) {
if (num === 0 || num === 1) {
return 1; // Base case: factorial of 0 and 1 is 1
}
let factorial = 1;
for (let i = 2; i <= num; i++) {
factorial *= i;
}
return factorial;
}

// Event listener for the button click


document.getElementById("calculateBtn").addEventListener("click", function() {
// Get the number entered by the user
let number = parseInt(document.getElementById("numberInput").value);

// Ensure the number is valid (non-negative integer)


if (isNaN(number) || number < 0) {
document.getElementById("result").textContent = "Please enter a valid non-negative number.";
} else {
// Calculate factorial and display the result
let factorialResult = calculateFactorial(number);
document.getElementById("result").textContent = "Factorial of " + number + " is " + factorialResult;
}
});
Output:

Fibonacci series up to that number


Description:
To design a function in JavaScript that calculates the Fibonacci series up to a given number and displays
the result using functions and events, you can implement a similar approach as before. The user will input
a number, and a button click will trigger the calculation of the Fibonacci series up to that number.

1. HTML: The user can enter a number in the input field, and the button triggers the Fibonacci
series calculation when clicked.
2. JavaScript:
o The generateFibonacci() function computes the Fibonacci series up to the provided
number.
 It starts with 0 and 1 (the first two numbers in the Fibonacci series).
 It continues adding numbers until the next number exceeds the given input.
o An event listener is added to the button to trigger the function when clicked.
o The user input is validated to ensure that it is a valid non-negative integer, and the
Fibonacci series is displayed below the button.

1. The user enters a number into the input field.


2. When the "Calculate Fibonacci Series" button is clicked, the generateFibonacci() function is
triggered.
3. The Fibonacci series up to the entered number is calculated, and the result is displayed.

Example Output:

 If the user enters 10, the output would be:


o "Fibonacci series up to 10 is: 0, 1, 1, 2, 3, 5, 8"

Source Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Fibonacci Series Calculator</title>
</head>
<body>
<h1>Fibonacci Series Calculator</h1>
<label for="numberInput">Enter a number: </label>
<input type="number" id="numberInput" min="0">
<button id="calculateBtn">Calculate Fibonacci Series</button>

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

<script src="script.js"></script>
</body>
</html>
// Function to calculate the Fibonacci series up to the given number
function generateFibonacci(n) {
let fibonacciSeries = [];
let a = 0, b = 1;

if (n === 0) {
return fibonacciSeries; // Return empty array if number is 0
}

fibonacciSeries.push(a); // Add the first number (0)

// Generate Fibonacci series up to the given number


while (b <= n) {
fibonacciSeries.push(b);
let temp = a + b;
a = b;
b = temp;
}

return fibonacciSeries;
}

// Event listener for the button click


document.getElementById("calculateBtn").addEventListener("click", function() {
// Get the number entered by the user
let number = parseInt(document.getElementById("numberInput").value);

// Ensure the number is valid (non-negative integer)


if (isNaN(number) || number < 0) {
document.getElementById("result").textContent = "Please enter a valid non-negative number.";
} else {
// Generate Fibonacci series and display the result
let fibonacciSeries = generateFibonacci(number);
document.getElementById("result").textContent = "Fibonacci series up to " + number + " is: " +
fibonacciSeries.join(", ");
}
});

Output:
Prime numbers up to that number
Description:
To design a JavaScript function that calculates the prime numbers up to a given number and displays the
result using functions and events, we can follow a similar approach as before. The user will input a
number, and upon clicking a button, the prime numbers up to that number will be calculated and
displayed.

1. HTML: The user inputs a number, and the button triggers the prime number calculation when
clicked. The result will be displayed in a paragraph (<p id="result"></p>).
2. JavaScript:
o The isPrime() function checks if a given number is prime.
 It first eliminates numbers less than or equal to 1.
 Then, it checks if the number is divisible by any number from 2 to the square
root of the number.
o The generatePrimeNumbers() function generates a list of prime numbers up to the input
number.
 It loops through numbers starting from 2 and calls isPrime() for each one.
o The event listener triggers the function when the button is clicked, validates the input,
and displays the result.

1. The user enters a number in the input field.


2. When the "Calculate Prime Numbers" button is clicked, the generatePrimeNumbers() function is
called.
3. The prime numbers up to the entered number are calculated and displayed.

Example Output:

 If the user enters 20, the output will be:


o "Prime numbers up to 20 are: 2, 3, 5, 7, 11, 13, 17, 19"
This approach ensures that only valid, prime numbers are included in the result.

Source Code:
Write a JavaScript for Design a appropriate function should be called to display Prime numbers up to that
number using Functions and Events

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Prime Number Finder</title>
</head>
<body>
<h2>Prime Number Finder</h2>
<label for="number">Enter a number:</label>
<input type="number" id="number" min="2">
<button onclick="displayPrimes()">Show Prime Numbers</button>

<h3>Prime Numbers:</h3>
<ul id="primeList"></ul>

<script>
// Function to check if a number is prime
function isPrime(num) {
if (num <= 1) return false;
for (let i = 2; i <= Math.sqrt(num); i++) {
if (num % i === 0) return false;
}
return true;
}

// Function to display prime numbers up to the given number


function displayPrimes() {
const inputNumber = document.getElementById('number').value;
const primeList = document.getElementById('primeList');
primeList.innerHTML = ''; // Clear previous list

// Loop through all numbers from 2 to the given number


for (let i = 2; i <= inputNumber; i++) {
if (isPrime(i)) {
const listItem = document.createElement('li');
listItem.textContent = i;
primeList.appendChild(listItem);
}
}
}
</script>
</body>
</html>

Output:
Palindrome or not
Description:
JavaScript example that checks if a given input is a palindrome (a word, phrase, or number that reads the
same backward as forward) using functions and events.

1. HTML Structure:
o The user inputs a word or phrase in a text field.
o When the user clicks the "Check Palindrome" button, the checkPalindrome() function is
triggered.
o The result (whether the input is a palindrome or not) is displayed below the button in a
<h3> element.
2. JavaScript:
o checkPalindrome():
 The function grabs the input from the user.
 It cleans the input by removing any non-alphanumeric characters (like spaces,
punctuation) and converts it to lowercase to ensure the comparison is case-
insensitive and ignores special characters.
 It then checks if the cleaned input is the same forwards and backwards by
reversing the string.
 If it is a palindrome, the result is shown in green; otherwise, it is shown in red.

How it works:

 The user enters a word or phrase and clicks the "Check Palindrome" button.
 The checkPalindrome() function processes the input, removes any non-alphanumeric characters,
and compares it with its reversed version.
 A message is displayed indicating whether the input is a palindrome or not.

Source Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Palindrome Checker</title>
</head>
<body>
<h2>Palindrome Checker</h2>
<label for="inputText">Enter a word or phrase:</label>
<input type="text" id="inputText">
<button onclick="checkPalindrome()">Check Palindrome</button>

<h3 id="result"></h3>

<script>
// Function to check if the input is a palindrome
function checkPalindrome() {
const inputText = document.getElementById('inputText').value;
const resultElement = document.getElementById('result');
// Remove non-alphanumeric characters and convert to lowercase
const cleanedInput = inputText.replace(/[^a-zA-Z0-9]/g, '').toLowerCase();

// Check if the cleaned input is the same forwards and backwards


const reversedInput = cleanedInput.split('').reverse().join('');

if (cleanedInput === reversedInput) {


resultElement.textContent = `"${inputText}" is a palindrome!`;
resultElement.style.color = "green";
} else {
resultElement.textContent = `"${inputText}" is NOT a palindrome.`;
resultElement.style.color = "red";
}
}
</script>
</body>
</html>

Output:
Design a HTML having a text box and four buttons named Factorial, Fibonacci, Prime, and Palindrome.
When a button is pressed an appropriate function should be called to display
 Factorial of that number
 Fibonacci series up to that number
 Prime numbers up to that number
 Is it palindrome or not
Description:

1. HTML Structure:
o The user enters a number in the text box.
o Four buttons trigger different operations:
 Factorial: Calculates the factorial of the entered number.
 Fibonacci: Displays the Fibonacci series up to the entered number.
Prime Numbers: Lists all prime numbers up to the entered number.
Palindrome: Checks if the entered number is a palindrome.
2. JavaScript Functions:
o calculateFactorial(): Calculates the factorial of the number by multiplying all integers
from 1 to the entered number.
o generateFibonacci(): Generates the Fibonacci series up to the entered number using a
loop.
o generatePrimes(): Loops through all numbers from 2 to the entered number, checking
for primes and collecting them.
o checkPalindrome(): Converts the number to a string and checks if it reads the same
backward.
3. Result Display:
o Each function updates its respective result section (e.g., factorial, Fibonacci series, prime
numbers, palindrome check) below the input box when the user presses a button.

 The user enters a number and clicks one of the buttons.


 The corresponding JavaScript function is called.
 The result for each operation is displayed below the input box in its respective section.

Source Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Math and String Operations</title>
<style>
#result {
margin-top: 20px;
}
.output {
margin: 10px 0;
}
</style>
</head>
<body>
<h2>Math and String Operations</h2>
<label for="inputNumber">Enter a number:</label>
<input type="number" id="inputNumber" min="1">
<button onclick="calculateFactorial()">Factorial</button>
<button onclick="generateFibonacci()">Fibonacci</button>
<button onclick="generatePrimes()">Prime Numbers</button>
<button onclick="checkPalindrome()">Palindrome Check</button>

<div id="result">
<div id="factorialResult" class="output"></div>
<div id="fibonacciResult" class="output"></div>
<div id="primeResult" class="output"></div>
<div id="palindromeResult" class="output"></div>
</div>

<script>
// Function to calculate the factorial of a number
function calculateFactorial() {
const num = document.getElementById('inputNumber').value;
const resultDiv = document.getElementById('factorialResult');
let factorial = 1;
for (let i = 1; i <= num; i++) {
factorial *= i;
}
resultDiv.textContent = `Factorial of ${num} is: ${factorial}`;
}
// Function to generate Fibonacci series up to a number
function generateFibonacci() {
const num = document.getElementById('inputNumber').value;
const resultDiv = document.getElementById('fibonacciResult');
let fibSeries = [];
let a = 0, b = 1;
while (a <= num) {
fibSeries.push(a);
let temp = a;
a = b;
b = temp + b;
}
resultDiv.textContent = `Fibonacci series up to ${num}: ${fibSeries.join(', ')}`;
}

// Function to generate prime numbers up to a number


function generatePrimes() {
const num = document.getElementById('inputNumber').value;
const resultDiv = document.getElementById('primeResult');
let primes = [];
for (let i = 2; i <= num; i++) {
if (isPrime(i)) {
primes.push(i);
}
}
resultDiv.textContent = `Prime numbers up to ${num}: ${primes.join(', ')}`;
}

// Helper function to check if a number is prime


function isPrime(n) {
if (n <= 1) return false;
for (let i = 2; i <= Math.sqrt(n); i++) {
if (n % i === 0) return false;
}
return true;
}

// Function to check if the input number is a palindrome


function checkPalindrome() {
const num = document.getElementById('inputNumber').value;
const resultDiv = document.getElementById('palindromeResult');
const numStr = num.toString();
const reversedNum = numStr.split('').reverse().join('');
if (numStr === reversedNum) {
resultDiv.textContent = `${num} is a palindrome!`;
} else {
resultDiv.textContent = `${num} is NOT a palindrome.`;
}
}
</script>
</body>
</html>
Output:
c. Write a program to validate the following fields in a registration page
i. Name (start with alphabet and followed by alphanumeric and the length should not be less than 6
characters)
ii. Mobile (only numbers and length 10 digits)
iii. E-mail (should contain format like [email protected])
Description:

1. HTML Form:
The form contains three fields: Name, Mobile, and Email.
o
Each field has an associated error message span (<span>) which is used to display
o
validation errors if the input does not meet the specified criteria.
2. JavaScript Validation Functions:
o validateName(name):
 Ensures the name starts with an alphabet letter, is followed by alphanumeric
characters, and has a minimum length of 6 characters.
 The regex pattern is ^[A-Za-z][A-Za-z0-9]{5,}$, where ^[A-Za-z] ensures it
starts with a letter, [A-Za-z0-9]{5,}$ ensures the rest are alphanumeric, and the
minimum length is 6 characters.
o validateMobile(mobile):
 Ensures the mobile number is exactly 10 digits. The regex pattern is ^\d{10}$,
where \d{10} ensures 10 digits are present.
o validateEmail(email):
 Ensures the email is in a proper format, like [email protected]. The regex pattern
is ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$ for basic email
validation.
3. Event Listener:
o The form has an event listener attached to its submit event. When the form is submitted,
the validation functions are called for each field.
o If any validation fails, the error messages are displayed, and form submission is
prevented using event.preventDefault().

 When the user clicks the "Register" button, the form submission is handled.
 The validation checks for each field (Name, Mobile, Email) are done, and if any field is invalid,
an appropriate error message is shown.
 If all fields are valid, the form would be submitted successfully.

Source Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Registration Form Validation</title>
<style>
.error {
color: red;
}
</style>
</head>
<body>
<h2>Registration Form</h2>
<form id="registrationForm">
<label for="name">Name (min 6 characters, alphanumeric, starts with alphabet):</label><br>
<input type="text" id="name" name="name" required><br>
<span id="nameError" class="error"></span><br>

<label for="mobile">Mobile (10 digits, numbers only):</label><br>


<input type="text" id="mobile" name="mobile" required><br>
<span id="mobileError" class="error"></span><br>

<label for="email">E-mail (format: [email protected]):</label><br>


<input type="email" id="email" name="email" required><br>
<span id="emailError" class="error"></span><br><br>

<button type="submit">Register</button>
</form>

<script>
// Function to validate the name field
function validateName(name) {
const nameRegex = /^[A-Za-z][A-Za-z0-9]{5,}$/; // Starts with a letter, followed by
alphanumeric, minimum length 6
return nameRegex.test(name);
}

// Function to validate the mobile field


function validateMobile(mobile) {
const mobileRegex = /^\d{10}$/; // 10 digits
return mobileRegex.test(mobile);
}

// Function to validate the email field


function validateEmail(email) {
const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/; // Standard email
format
return emailRegex.test(email);
}

// Handling form submission and validation


document.getElementById('registrationForm').addEventListener('submit', function(event) {
let isValid = true;

// Clear previous error messages


document.getElementById('nameError').textContent = '';
document.getElementById('mobileError').textContent = '';
document.getElementById('emailError').textContent = '';

const name = document.getElementById('name').value;


const mobile = document.getElementById('mobile').value;
const email = document.getElementById('email').value;

// Validate Name
if (!validateName(name)) {
document.getElementById('nameError').textContent = 'Name must start with a letter, be
alphanumeric, and at least 6 characters long.';
isValid = false;
}

// Validate Mobile
if (!validateMobile(mobile)) {
document.getElementById('mobileError').textContent = 'Mobile must be exactly 10 digits.';
isValid = false;
}

// Validate Email
if (!validateEmail(email)) {
document.getElementById('emailError').textContent = 'Email must be in the correct format
([email protected]).';
isValid = false;
}

// If any validation fails, prevent form submission


if (!isValid) {
event.preventDefault();
}
});
</script>
</body>
</html>

Output:

You might also like