FSD - Experiment - IX - For II-II-CSE
FSD - Experiment - IX - For II-II-CSE
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>).
<!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;
}
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.
Example Output:
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
}
return fibonacciSeries;
}
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.
Example Output:
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;
}
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();
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.
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(', ')}`;
}
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>
<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);
}
// 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;
}
Output: