0% found this document useful (0 votes)
2 views10 pages

WC 2

The document contains multiple JavaScript assignments including code for a digital clock, comparison of ES5 and ES6 functions, background color changes, form validation, cookie setting, and an alumni information form. Each section provides HTML, CSS, and JavaScript code examples for specific functionalities. The document serves as a comprehensive guide for implementing various web development tasks using JavaScript.

Uploaded by

kajalkupale0
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)
2 views10 pages

WC 2

The document contains multiple JavaScript assignments including code for a digital clock, comparison of ES5 and ES6 functions, background color changes, form validation, cookie setting, and an alumni information form. Each section provides HTML, CSS, and JavaScript code examples for specific functionalities. The document serves as a comprehensive guide for implementing various web development tasks using JavaScript.

Uploaded by

kajalkupale0
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
You are on page 1/ 10

ASSINGNMENT 02

1. Write a JavaScript code for displaying a digital clock on a web page


• JS
function updateClock() {
const now = new Date();
const hours = String(now.getHours()).padStart(2, '0');
const minutes = String(now.getMinutes()).padStart(2, '0');
const seconds = String(now.getSeconds()).padStart(2, '0');

const timeString = `${hours}:${minutes}:${seconds}`;


document.getElementById('clock').textContent = timeString;
}

setInterval(updateClock, 1000);
updateClock(); // Initial call to display clock immediately

• HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Digital Clock</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div id="clock" class="clock"></div>
<script src="script.js"></script>
</body>
</html>

• CSS
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background-color: #282c34;
color: #61dafb;
font-family: 'Arial', sans-serif;
}

.clock {
font-size: 3rem;
background: #000;
padding: 20px;
border-radius: 10px;
text-align: center;
}
2. Compare ES 5 and ES 6. Give an example of the Anonymous and Arrow function inES6

• Anonymous Function (ES6)


An anonymous function is a function that does not have a name. It is often used as an argument
to another function or for inline function definitions.

Example
const numbers = [1, 2, 3, 4, 5];

// Anonymous function used with the map method


const doubled = numbers.map(function(number) {
return number * 2;
});

console.log(doubled); // Output: [2, 4, 6, 8, 10]


• Arrow Function (ES6)
Arrow functions provide a concise syntax and do not have their own this context, which makes
them ideal for many cases involving callbacks and inline function definitions.

Example
const numbers = [1, 2, 3, 4, 5];

// Arrow function used with the map method


const doubled = numbers.map(number => number * 2);

console.log(doubled); // Output: [2, 4, 6, 8, 10]

Both types of functions can be useful depending on the situation, but arrow functions often provide
a cleaner and more concise way to handle short functions and callbacks.

3. Write a code in JavaScript for any one of the following.

1) To change the background color of the web page automatically after every 5seconds.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Change Background Color</title>
<style>
body {
transition: background-color 1s; /* Smooth transition for color change */
}
</style>
</head>
<body>
<script>
const colors = ['#FF6347', '#4682B4', '#32CD32', '#FFD700', '#FF69B4'];
let currentIndex = 0;

function changeBackgroundColor() {
document.body.style.backgroundColor = colors[currentIndex];
currentIndex = (currentIndex + 1) % colors.length;
}

setInterval(changeBackgroundColor, 5000);
</script>
</body>
</html>
2) To display three radio buttons on the web page, namely, “Red”, “Blue” and “Green”.
Selecting any button changes the background color as per the name of the button.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Change Background Color</title>
</head>
<body>
<h2>Select a color:</h2>
<input type="radio" id="red" name="color" value="red">
<label for="red">Red</label><br>
<input type="radio" id="blue" name="color" value="blue">
<label for="blue">Blue</label><br>
<input type="radio" id="green" name="color" value="green">
<label for="green">Green</label>

<script>
function changeBackgroundColor(event) {
document.body.style.backgroundColor = event.target.value;
}

const radios = document.querySelectorAll('input[name="color"]');


radios.forEach(radio => {
radio.addEventListener('change', changeBackgroundColor);
});
</script>
</body>
</html>

4. Write a JavaScript code to set a cookie on the user's computer.


function setCookie(name, value, days) {
let expires = "";
if (days) {
const date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "expires=" + date.toUTCString();
}
document.cookie = name + "=" + (value || "") + ";" + expires + ";path=/";
}
// Example usage
setCookie('username', 'JohnDoe', 7); // Sets a cookie named 'username' with the value
'JohnDoe' that expires in 7 days
5. Write JavaScript to validate Username, Password and Email. Username and Password
should not be blank and minimum length of password =8. Email should have @
character.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Validation</title>
<style>
.error {
color: red;
font-size: 0.875rem;
}
</style>
</head>
<body>
<h2>Form Validation</h2>
<form id="myForm">
<label for="username">Username:</label>
<input type="text" id="username" name="username"><br>
<span id="usernameError" class="error"></span><br>

<label for="password">Password:</label>
<input type="password" id="password" name="password"><br>
<span id="passwordError" class="error"></span><br>

<label for="email">Email:</label>
<input type="email" id="email" name="email"><br>
<span id="emailError" class="error"></span><br>

<input type="submit" value="Submit">


</form>

<script>
document.getElementById('myForm').addEventListener('submit', function(event) {
event.preventDefault(); // Prevent form submission

// Clear previous error messages


document.getElementById('usernameError').textContent = '';
document.getElementById('passwordError').textContent = '';
document.getElementById('emailError').textContent = '';

// Get form values


const username = document.getElementById('username').value.trim();
const password = document.getElementById('password').value.trim();
const email = document.getElementById('email').value.trim();

// Validation flags
let isValid = true;

// Validate Username
if (username === '') {
document.getElementById('usernameError').textContent = 'Username cannot be
blank.';
isValid = false;
}

// Validate Password
if (password === '') {
document.getElementById('passwordError').textContent = 'Password cannot be
blank.';
isValid = false;
} else if (password.length < 8) {
document.getElementById('passwordError').textContent = 'Password must be at least
8 characters long.';
isValid = false;
}

// Validate Email
if (email === '') {
document.getElementById('emailError').textContent = 'Email cannot be blank.';
isValid = false;
} else if (!email.includes('@')) {
document.getElementById('emailError').textContent = 'Email must contain "@"
character.';
isValid = false;
}

if (isValid) {
// If valid, submit the form or perform desired action
alert('Form submitted successfully!');
}
});
</script>
</body>
</html>
6. Write a JavaScript to accept two numbers and display their sum using pop up box.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sum of Two Numbers</title>
</head>
<body>
<script>
// Function to prompt user for two numbers and display their sum
function calculateSum() {
// Prompt user for the first number
const num1 = parseFloat(prompt("Enter the first number:"));

// Prompt user for the second number


const num2 = parseFloat(prompt("Enter the second number:"));

// Check if inputs are valid numbers


if (isNaN(num1) || isNaN(num2)) {
alert("Please enter valid numbers.");
} else {
// Calculate the sum
const sum = num1 + num2;

// Display the sum in an alert box


alert("The sum of " + num1 + " and " + num2 + " is " + sum + ".");
}
}

// Call the function to execute on page load


calculateSum();
</script>
</body>
</html>
7. Write the code to process online Alumni information for your college. Create a form to
geta name, date of birth and email id. Use check boxes for taking hobbies and radio
buttons for selecting branch. Write JavaScript code to validate the following.
-User has to fill all the fields prior to the form submission.
- Valid email id (@ and .)
-Age validation using DOB (>=22 years)

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Alumni Information Form</title>
<style>
.error {
color: red;
font-size: 0.875rem;
}
</style>
</head>
<body>
<h2>Alumni Information Form</h2>
<form id="alumniForm">
<label for="name">Name:</label>
<input type="text" id="name" name="name"><br>
<span id="nameError" class="error"></span><br>

<label for="dob">Date of Birth:</label>


<input type="date" id="dob" name="dob"><br>
<span id="dobError" class="error"></span><br>

<label for="email">Email:</label>
<input type="email" id="email" name="email"><br>
<span id="emailError" class="error"></span><br>

<fieldset>
<legend>Hobbies:</legend>
<input type="checkbox" id="hobby1" name="hobbies" value="Reading">
<label for="hobby1">Reading</label><br>
<input type="checkbox" id="hobby2" name="hobbies" value="Traveling">
<label for="hobby2">Traveling</label><br>
<input type="checkbox" id="hobby3" name="hobbies" value="Sports">
<label for="hobby3">Sports</label>
</fieldset><br>

<fieldset>
<legend>Branch:</legend>
<input type="radio" id="branch1" name="branch" value="Computer Science">
<label for="branch1">Computer Science</label><br>
<input type="radio" id="branch2" name="branch" value="Electrical">
<label for="branch2">Electrical</label><br>
<input type="radio" id="branch3" name="branch" value="Mechanical">
<label for="branch3">Mechanical</label>
</fieldset><br>
<input type="submit" value="Submit">
</form>

<script>
document.getElementById('alumniForm').addEventListener('submit', function(event) {
event.preventDefault(); // Prevent form submission

// Clear previous error messages


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

// Get form values


const name = document.getElementById('name').value.trim();
const dob = document.getElementById('dob').value;
const email = document.getElementById('email').value.trim();
const hobbies = document.querySelectorAll('input[name="hobbies"]:checked');
const branch = document.querySelector('input[name="branch"]:checked');

let isValid = true;

// Validate Name
if (name === '') {
document.getElementById('nameError').textContent = 'Name is required.';
isValid = false;
}

// Validate Date of Birth and Age


if (dob === '') {
document.getElementById('dobError').textContent = 'Date of Birth is required.';
isValid = false;
} else {
const birthDate = new Date(dob);
const today = new Date();
const age = today.getFullYear() - birthDate.getFullYear();
const month = today.getMonth() - birthDate.getMonth();

if (month < 0 || (month === 0 && today.getDate() < birthDate.getDate())) {


age--;
}

if (age < 22) {


document.getElementById('dobError').textContent = 'You must be at least 22
years old.';
isValid = false;
}
}

// Validate Email
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailPattern.test(email)) {
document.getElementById('emailError').textContent = 'Please enter a valid email
address.';
isValid = false;
}

// Check if Branch is Selected


if (!branch) {
document.getElementById('branchError').textContent = 'Please select a branch.';
isValid = false;
}

// If all validations pass


if (isValid) {
alert('Form submitted successfully!');
// Perform form submission or further actions here
}
});
</script>
</body>
</html>

You might also like