0% found this document useful (0 votes)
78 views

Css Practise Test Model Answer 2 by Rit

css answers

Uploaded by

riteshdebadwar
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)
78 views

Css Practise Test Model Answer 2 by Rit

css answers

Uploaded by

riteshdebadwar
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/ 28

Css Model Answer 2

Q.1) Write a Javascript to design a form to accept values for user ID &
password
Ans: <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>User Login Form</title>
</head>
<body>

<h2>User Login</h2>
<form id="loginForm">
<label for="userId">User ID:</label>
<input type="text" name="userId" required><br><br>

<label for="password">Password:</label>
<input type="password" name="password" required><br><br>

<button type="button" onclick="submitForm()">Submit</button>


</form>

<script>
function submitForm() {
var userId = document.loginForm.userId.value;
var password = document.loginForm.password.value;

if (userId && password) {


document.write("<h2>Form Submitted</h2>");
document.write("User ID: " + userId + "<br>");
document.write("Password: " + password + "<br>");
} else {
document.write("Please fill in both fields.");
}
}
</script>

</body>
</html>
Q.2) State any two properties and methods of location object
Ans: Two Properties of the location Object:
1. location.href:
o Represents the entire URL of the current page (e.g.,
https://example.com/page.html).
o You can use it to get or set the URL. Setting this property causes
the browser to load the new URL.
javascript
Copy code
console.log(location.href); // Outputs the current page URL
location.href = "https://example.com"; // Redirects to another URL
2. location.hostname:
o Returns the domain name of the web host (e.g., example.com).
console.log(location.hostname);
Two Methods of the location Object:
1. location.reload():
o Reloads the current document from the server.
location.reload();
2. location.assign():
o Loads a new document at the specified URL, similar to setting
location.href, but without storing the current page in the session
history.
location.assign("https://example.com");

Q.3) Differentiate between session cookies and persistent cookies.


Ans:

Feature Session Cookies Persistent Cookies

Temporary; exists only during Long-lasting; remains on the user's


Lifespan
the browser session. device after the session ends.

Stored in memory and not Stored on the user's hard drive and
Storage
saved to the user's hard drive. can persist across sessions.

Can have a specific expiration date


Deleted automatically when
Expiration set by the Expires or Max-Age
the browser is closed.
attribute.

Suitable for tracking user Used for remembering user preferences,


Use activity during a single logins, or any information that needs to
Cases session (e.g., temporary persist between sessions (e.g.,
shopping cart). "Remember Me" login).

Security Considered more secure, as Less secure if not encrypted


they do not persist on the properly, as they stay on the user's
user's system after the session device and could be exploited if
ends. sensitive data is stored.

Q.4) State what is a cookie ? Explain its need. State characteristics of


persistent cookies.
Ans:
A cookie is a small piece of data stored on the user's computer by the web
browser while browsing a website. Cookies are used to remember
information about the user and their preferences, enabling a personalized
and efficient browsing experience.
Need for Cookies
Cookies serve several important purposes:
1. Session Management:
o Cookies help maintain user sessions on websites, allowing users
to stay logged in as they navigate through different pages. This is
particularly important for e-commerce sites, online banking, and
social media platforms.
2. Personalization:
o Websites can use cookies to remember user preferences, such as
language settings, themes, or layout choices, providing a tailored
experience on subsequent visits.
3. Tracking and Analytics:
o Cookies are used to collect data on user behavior, such as pages
visited, time spent on the site, and interactions. This information
helps website owners understand user preferences and improve
their services.
4. Advertising:
o Cookies allow advertisers to track users across different websites
and deliver targeted ads based on their browsing habits,
increasing the relevance of advertisements.
Characteristics of Persistent Cookies
Persistent cookies, also known as permanent cookies or stored cookies, have
specific characteristics that differentiate them from session cookies:
1. Lifespan:
o Persistent cookies have a specified expiration date set by the
server. They remain on the user's device even after the browser
is closed and are available for future visits until they expire or are
deleted by the user.
2. Data Storage:
o They can store user information over long periods, which is
beneficial for remembering login credentials, preferences, and
other data without requiring users to re-enter it every time they
visit the site.
3. Usage:
o Persistent cookies are typically used for personalization,
analytics, and advertising. They help provide a consistent
experience across multiple sessions, allowing websites to
remember user settings and behavior over time.

Q.5) Explain how to create and read Persistent Cookies in JavaScript with
example.
Ans:
creating and reading persistent cookies in JavaScript is straightforward.
Persistent cookies are stored on the user's device until they expire or are
deleted, allowing you to maintain user preferences or session data across
multiple visits to a website.
Creating Persistent Cookies
To create a persistent cookie in JavaScript, you use the document.cookie
property and specify the cookie's name, value, expiration date, path, and
other attributes.
document.cookie = "name=value; expires=expirationDate; path=/;
SameSite=Strict; Secure";

example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Cookie example</title>
</head>
<body>
<h1>Cookies</h1>
<script>
document.cookie = "username = Ritesh value = white; expires =
thursday,03oct,9:00:00";

alert(document.cookie);

</script>

</body>
</html>

Q.6) List ways of protecting your webpage and describe any one of them
Ans:
1) Input Validation:
 Ensure that all user inputs are properly validated on both the client and
server sides to prevent injection attacks (e.g., SQL injection, XSS).
2) HTTPS (SSL/TLS):
 Use HTTPS to encrypt data transmitted between the user’s browser
and your server, protecting against eavesdropping and man-in-the-
middle attacks.
3) Content Security Policy (CSP):
 Implement a CSP to restrict which resources (e.g., scripts, stylesheets)
can be loaded by the webpage, mitigating risks from XSS attacks.
4) Cross-Origin Resource Sharing (CORS):
 Configure CORS policies to control which domains can access resources
on your server, preventing unauthorized cross-origin requests.
5) Secure Authentication:
 Use secure authentication methods, such as OAuth, and implement
features like multi-factor authentication (MFA) to protect user
accounts.
6) Session Management:
 Implement secure session management practices, including session
timeouts and secure cookie attributes (e.g., HttpOnly, Secure).

Q.7) Write a JavaScript program to create read, update and delete cookies.
Ans:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple Cookie Operations</title>
</head>
<body>
<h1>Simple Cookie Operations</h1>

<script>

document.write("<h3>Create Cookie:</h3>");
document.cookie = "username=JohnDoe; path=/";
document.write("Created Cookie: " + document.cookie + "<br>");

document.write("<h3>Read Cookie:</h3>");
document.write("All Cookies: " + document.cookie + "<br>");

document.write("<h3>Update Cookie:</h3>");
document.cookie = "username=JaneDoe; path=/";
document.write("Updated Cookie: " + document.cookie + "<br>");

document.write("<h3>Delete Cookie:</h3>");
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC;
path=/";
document.write("Cookie After Deletion: " + document.cookie);
</script>
</body>
</html>
Q.8) Enlist and explain different properties of Form tag.
Ans:
1. action
 Description: Specifies where the form data will be sent when the form
is submitted.
 Example: action="submit_form.php"
 Explanation: The form data will be sent to the URL specified in the
action attribute, typically a server-side script like PHP or Node.js that
processes the input.
2. method
 Description: Specifies the HTTP method used to send form data (GET or
POST).
 Example: method="post"
 Explanation:
o GET: Sends form data appended to the URL, useful for retrieving
data.
o POST: Sends form data as part of the request body, useful for
sending sensitive or large amounts of data.
3. enctype
 Description: Specifies how the form data should be encoded when sent
to the server. It is important when uploading files.
 Example: enctype="multipart/form-data"
 Explanation:
o application/x-www-form-urlencoded (default): Data is encoded
as key-value pairs.
o multipart/form-data: Used when the form includes file uploads.
o text/plain: Data is sent as plain text.
4. target
 Description: Specifies where to display the response after submitting
the form.
 Example: target="_blank"
 Explanation:
o _self (default): Opens the response in the same window.
o _blank: Opens the response in a new tab or window.
o _parent: Loads the response into the parent frame.
o _top: Loads the response into the full body of the window,
removing any frames.

Q.9) What is the difference between Get and Post methods of a Form tag.
Explain with an example.
Ans:
1. GET Method
 Description: The GET method sends form data appended to the URL as
query parameters.
 Characteristics:
o Data is sent as a query string in the URL.
o The data is visible in the browser's address bar.
o Typically used for retrieving data (non-sensitive information).
o Has a size limit (around 2048 characters).
o Form submissions can be bookmarked or shared since the data is
in the URL.
 Use Case: Suitable for search forms or when retrieving data without
modifying anything on the server.
 Example:
<form action="/search" method="get">
<label for="query">Search:</label>
<input type="text" id="query" name="query">
<input type="submit" value="Search">
</form>
 Explanation: In this example, if the user types "JavaScript" and submits
the form, the browser will send a request to /search?query=JavaScript.
The server will receive this data and process it to display search results.
2. POST Method
 Description: The POST method sends form data in the body of the HTTP
request, making it invisible to the user.
 Characteristics:
o Data is sent in the request body, not the URL.
o More secure than GET as data is not visible in the URL.
o No size limitation on the amount of data being sent (can send
large amounts, including files).
o Typically used for submitting sensitive information like
passwords, login details, or when adding/modifying server data.
 Use Case: Suitable for forms involving sensitive data (e.g., login,
registration) or when sending large amounts of data (e.g., file uploads).
 Example:

<form action="/login" method="post">


<label for="username">Username:</label>
<input type="text" id="username" name="username">
<br>
<label for="password">Password:</label>
<input type="password" id="password" name="password">
<br>
<input type="submit" value="Login">
</form>
 Explanation: In this example, when the user submits the form, the
browser sends the username and password data in the body of the
HTTP request to /login. The data will not be visible in the URL.
Key Differences Between GET and POST:

Aspect GET Method POST Method

Data is appended to the URL


Data Data is sent in the request body
and visible in the address
Visibility and is not visible in the URL.
bar.

Limited to around 2048 No size limit. Suitable for large


Size Limit
characters. data or file uploads.

Less secure, as data is More secure, as data is hidden


Security
exposed in the URL. from the URL.

Used for retrieving data Used for sending sensitive or


Use Case (e.g., search queries, filter large data (e.g., login forms, file
options). uploads).

Can be bookmarked or Cannot be bookmarked since


Bookmarking
shared easily. data is not in the URL.

Data is cached in the


Caching Data is not cached.
browser.

Q.10) Write a JavaScript function that will open new window when the user
will clicks on the button.
Ans:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Open New Window</title>
</head>
<body>

<h2>Click the Button to Open a New Window</h2>

<button onclick="openNewWindow()">Open Window</button>

<script>
function openNewWindow() {
// Open a new window
window.open("https://www.example.com", "_blank",
"width=600,height=400");
}
</script>

</body>
</html>

Q.11) Design a webpage that displays a form that contains an input for user
name and password. User is prompted to enter the input user name
and password and password become value of the cookies. Write the
JavaScript function for storing the cookies
Ans:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Store Username and Password as Cookies</title>
</head>
<body>

<h2>Enter Username and Password</h2>

<form>
<label for="username">Username:</label>
<input type="text" id="username" placeholder="Enter your username"
required>
<br><br>
<label for="password">Password:</label>
<input type="password" id="password" placeholder="Enter your
password" required>
<br><br>
<button type="button" onclick="storeCookies()">Submit</button>
</form>

<h3>Stored Cookies:</h3>
<div id="cookieDisplay"></div>

<script>
// Function to store cookies for username and password
function storeCookies() {
var username = document.getElementById('username').value;
var password = document.getElementById('password').value;

if (username !== "" && password !== "") {


// Set the cookies to expire in 7 days
var expiryDate = new Date();
expiryDate.setTime(expiryDate.getTime() + (7*24*60*60*1000));
var expires = "expires=" + expiryDate.toUTCString();

document.cookie = "username=" + username + "; " + expires + ";


path=/";
document.cookie = "password=" + password + "; " + expires + ";
path=/";

document.getElementById('cookieDisplay').innerHTML = "Cookies
Created: " + document.cookie;
} else {
alert("Please enter both username and password.");
}
}
document.getElementById('cookieDisplay').innerHTML = "Current
Cookies: " + document.cookie;
</script>

</body>
</html>
Q.12) Explain how to evaluate Radiobutton in JavaScript with suitable
example.
Ans:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Open Window with Frames</title>
</head>
<body>

<h2>Click the button to open a new window with frames</h2>


<button onclick="openNewWindow()">Open New Window</button>

<script>
function openNewWindow() {
// Open a new window
var newWindow = window.open("", "newWindow",
"width=600,height=400");

// Create frameset in the new window


newWindow.document.write(`
<html>
<head><title>New Window with Frames</title></head>
<body>
<frameset cols="50%,50%">
<frame name="leftFrame" id="leftFrame">
<frame name="rightFrame" id="rightFrame">
</frameset>
</body>
</html>
`);

// Add content to the left frame (button)


newWindow.frames['leftFrame'].document.write(`
<html>
<body>
<h3>Click the button to open an image in the second frame</h3>
<button
onclick="parent.frames['rightFrame'].location.href='https://www.example.co
m/image.jpg';">Click Here!</button>
</body>
</html>
`);

// The right frame will display the image after clicking the button
}
</script>

</body>
</html>
Q.13) Write a javascript to create option list containing list of images and
then display images in new window as per selection.
Ans:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Image Selector</title>
<script>
function openImage() {
// Get the selected image option
var selectElement = document.getElementById("imageSelect");
var selectedImage = selectElement.value;

// Open a new window


var newWindow = window.open("", "ImageWindow",
"width=600,height=400");

// Write the image HTML to the new window


newWindow.document.write(`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Selected Image</title>
</head>
<body>
<h2>Selected Image:</h2>
<img src="${selectedImage}" alt="Selected Image" style="max-
width: 100%; height: auto;">
</body>
</html>
`);
newWindow.document.close(); // Close the document stream
}
</script>
</head>
<body>

<h2>Select an Image</h2>
<select id="imageSelect">
<option value="">--Select an Image--</option>
<option
value="https://via.placeholder.com/300x200?text=Image+1">Image
1</option>
<option
value="https://via.placeholder.com/300x200?text=Image+2">Image
2</option>
<option
value="https://via.placeholder.com/300x200?text=Image+3">Image
3</option>
<option
value="https://via.placeholder.com/300x200?text=Image+4">Image
4</option>
</select>
<br><br>
<button onclick="openImage()">Display Image</button>

</body>
</html>

Q.14) Write HTML script that will display following structure.


+------------------------------+
| Registration |
+------------------------------+
Name: [__________]
Email ID: [__________]
Pin Code: [__________]
[ Submit ]
+------------------------------+
Ans:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Registration Form</title>
</head>
<body>

<h2>Registration</h2>
<form action="#" method="post">
<label for="name">Name:</label><br>
<input type="text" id="name" name="name" required><br><br>

<label for="email">Email ID:</label><br>


<input type="email" id="email" name="email" required><br><br>

<label for="pincode">Pin Code:</label><br>


<input type="text" id="pincode" name="pincode" required><br><br>

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


</form>

</body>
</html>

Q.15) Write the JavaScript code for below operations: (1) Name, Email &amp;
Pin
Code should not be blank. (2) Pin Code must contain 6 digits &amp; it should
not be accept any characters.
Ans:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Registration Form</title>
<script>
function validateForm() {

var name = document.nameForm.name.value;


var email = document.nameForm.email.value;
var pincode = document.nameForm.pincode.value;

if (name === "" || email === "" || pincode === "") {


alert("Name, Email, and Pin Code cannot be blank.");
return false;
}

if (!/^\d{6}$/.test(pincode)) {
alert("Pin Code must contain exactly 6 digits and no characters.");
return false; // Prevent form submission
}

alert("Form submitted successfully!");


return true; // Allow form submission
}
</script>
</head>
<body>

<h2>Registration</h2>

<form name="nameForm" onsubmit="return validateForm();">


<label for="name">Name:</label><br>
<input type="text" id="name" name="name" required><br><br>

<label for="email">Email ID:</label><br>


<input type="email" id="email" name="email" required><br><br>

<label for="pincode">Pin Code:</label><br>


<input type="text" id="pincode" name="pincode" required><br><br>

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


</form>

</body>
</html>

Q.16) Write a HTML script which displays 2 radio buttons to the users for
fruits and vegetables and 1 option list. When user select fruits radio
button option list should present only fruits names to the user &amp; when
user select vegetable radio button option list should present only
vegetable names to the user.
Ans:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Fruits and Vegetables Selection</title>
<script>
function updateOptions() {
// Get the selected value of the radio buttons
var fruitVegetable = document.getElementsByName("fruitVegetable");
var selectedValue;

// Determine which radio button is selected


for (var i = 0; i < fruitVegetable.length; i++) {
if (fruitVegetable[i].checked) {
selectedValue = fruitVegetable[i].value;
break;
}
}

// Clear existing options


document.getElementById("options").innerHTML = "";

// Write new options based on selection


if (selectedValue === "fruits") {
document.write('<option value="Apple">Apple</option>');
document.write('<option value="Banana">Banana</option>');
document.write('<option value="Cherry">Cherry</option>');
document.write('<option value="Mango">Mango</option>');
document.write('<option value="Orange">Orange</option>');
} else if (selectedValue === "vegetables") {
document.write('<option value="Carrot">Carrot</option>');
document.write('<option value="Broccoli">Broccoli</option>');
document.write('<option value="Spinach">Spinach</option>');
document.write('<option value="Potato">Potato</option>');
document.write('<option value="Tomato">Tomato</option>');
}
}
</script>
</head>
<body>

<h2>Select Fruits or Vegetables</h2>

<label>
<input type="radio" name="fruitVegetable" value="fruits"
onclick="updateOptions()" checked>
Fruits
</label>
<label>
<input type="radio" name="fruitVegetable" value="vegetables"
onclick="updateOptions()">
Vegetables
</label>

<br><br>

<label for="options">Select an option:</label>


<select id="options">
<!-- Options will be populated here -->
</select>

</body>
</html>

Q.17) Describe how to read cookie value and write a cookie value. Explain
with example.
Ans:
Cookies are small pieces of data stored on the client-side by the browser.
They can be used to save user preferences, session information, and other
small amounts of data that persist between page loads. In JavaScript, you can
create, read, and delete cookies using the document.cookie property.
Writing a Cookie
To write a cookie in JavaScript, you can set the document.cookie property.
The syntax for writing a cookie is as follows:
javascript
Copy code
document.cookie = "key=value; expires=date; path=/";
 key: The name of the cookie.
 value: The value of the cookie.
 expires: Optional. The date when the cookie expires. If not set, the
cookie is a session cookie and will be deleted when the browser closes.
 path: Optional. The path on the server where the cookie will be
available. The default is the current path of the document.
Reading a Cookie
To read cookies, you can access the document.cookie property, which returns
a string containing all cookies associated with the current document. You can
split this string to get individual cookies.

Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Cookie example</title>
</head>
<body>
<h1>Cookies</h1>
<script>
document.cookie = "username = Ritesh value = white; expires =
thursday,03oct,9:00:00";

alert(document.cookie);

</script>

</body>
</html>

You might also like