Chapter 8
Web Technology
TU BSc CSIT past exam questions
Past questions and answers
70 questions set from this chapter. Most repeated first.
- 2076 · 10 marks
Create web form for book search catalog. The form should contain a dropdown defining search type, a text box for search keyword, a radio button for download type true or false, now write PHP script to store data from the form into database table and also retrive the results from stored table in a new page.
Answer
Database (MySQL):
CREATE DATABASE library;
USE library;
CREATE TABLE book_search (
id INT AUTO_INCREMENT PRIMARY KEY,
search_type VARCHAR(20) NOT NULL,
keyword VARCHAR(100) NOT NULL,
download VARCHAR(5) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
search.html (the web form)
<!DOCTYPE html>
<html>
<head><title>Book Search Catalog</title></head>
<body>
<h2>Book Search</h2>
<form action="save.php" method="post">
<label for="type">Search type:</label>
<select name="search_type" id="type">
<option value="title">Title</option>
<option value="author">Author</option>
<option value="isbn">ISBN</option>
<option value="subject">Subject</option>
</select><br><br>
<label for="kw">Keyword:</label>
<input type="text" name="keyword" id="kw" required><br><br>
Download:
<input type="radio" name="download" value="true" checked> True
<input type="radio" name="download" value="false"> False<br><br>
<input type="submit" value="Search">
</form>
</body>
</html>
save.php (stores the data)
<?php
$conn = new mysqli("localhost", "root", "", "library");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$type = $_POST['search_type'];
$keyword = $_POST['keyword'];
$download = $_POST['download'];
$stmt = $conn->prepare(
"INSERT INTO book_search (search_type, keyword, download) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $type, $keyword, $download);
if ($stmt->execute()) {
header("Location: result.php"); // go to the new page
exit;
} else {
echo "Error: " . $stmt->error;
}
$stmt->close();
$conn->close();
?>
result.php (retrieves the stored results in a new page)
<?php
$conn = new mysqli("localhost", "root", "", "library");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$result = $conn->query("SELECT * FROM book_search ORDER BY id DESC");
?>
<!DOCTYPE html>
<html>
<head><title>Stored Searches</title></head>
<body>
<h2>Stored Search Records</h2>
<table border="1" cellpadding="5">
<tr><th>ID</th><th>Type</th><th>Keyword</th><th>Download</th><th>Time</th></tr>
<?php while ($row = $result->fetch_assoc()) { ?>
<tr>
<td><?= $row['id'] ?></td>
<td><?= htmlspecialchars($row['search_type']) ?></td>
<td><?= htmlspecialchars($row['keyword']) ?></td>
<td><?= $row['download'] ?></td>
<td><?= $row['created_at'] ?></td>
</tr>
<?php } ?>
</table>
<a href="search.html">New search</a>
</body>
</html>
<?php $conn->close(); ?>
A prepared statement is used to prevent SQL injection, and htmlspecialchars() prevents XSS when the data is displayed.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2076 · 10 marks
How can you create objects in Javascript? Create a HTML page containing a division with image and its description in paragraph. Write a javascript function to change the value of description in the paragraph during onmouseover and mouseout event on the image.
Answer
Creating objects in JavaScript
JavaScript objects are collections of properties (name-value pairs) and methods. They can be created in these ways:
- Object literal
var student = { name: "Ram", age: 20, show: function () { return this.name; } };
new Object()
var s = new Object();
s.name = "Ram";
s.age = 20;
- Constructor function with
new
function Student(name, age) {
this.name = name;
this.age = age;
}
var s1 = new Student("Sita", 21);
Object.create(proto), which creates an object with a given prototype.- ES6
class
class Student {
constructor(name) { this.name = name; }
}
var s2 = new Student("Hari");
HTML page with image and description changing on mouse events
<!DOCTYPE html>
<html>
<head>
<title>Image Description</title>
<script>
function changeText(text) {
document.getElementById("desc").innerHTML = text;
}
</script>
</head>
<body>
<div id="box">
<img src="mountain.jpg" alt="Mountain" width="300"
onmouseover="changeText('Mount Everest, the highest peak in the world.')"
onmouseout="changeText('Move the mouse over the image to see details.')">
<p id="desc">Move the mouse over the image to see details.</p>
</div>
</body>
</html>
When the pointer enters the image, onmouseover calls changeText() and the paragraph text is replaced using the innerHTML property found with getElementById. When the pointer leaves, onmouseout restores the original text.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2076 · 10 marks
How positioning of HTML elements can be done using CSS? Create a HTML page with a div with some content and two paragraph with some contents having id p1 and p2. Write external CSS for the div tag having fixed position with border style solid and width 2px. the p1 should have relative position. The font type of p1 should be Arial and color should be red. The p2 have absolute position with top 0px and left 200px.
Answer
Positioning in CSS
The position property decides how an element is placed in the page, and the top, right, bottom and left properties then offset it.
| Value | Behaviour |
|---|---|
static | Default; element stays in the normal flow, offsets have no effect. |
relative | Placed in normal flow, then offset from its own normal position; the original space is kept. |
absolute | Removed from flow and positioned relative to the nearest positioned ancestor (or the page if none). |
fixed | Positioned relative to the browser viewport; does not move on scrolling. |
sticky | Behaves as relative until a scroll threshold is reached, then sticks like fixed. |
z-index controls the stacking order of positioned elements.
page.html
<!DOCTYPE html>
<html>
<head>
<title>CSS Positioning</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div>This is a div with fixed position and a solid border.</div>
<p id="p1">This is paragraph one with relative position.</p>
<p id="p2">This is paragraph two with absolute position.</p>
</body>
</html>
style.css (external CSS)
div {
position: fixed;
border-style: solid;
border-width: 2px;
}
#p1 {
position: relative;
font-family: Arial, sans-serif;
color: red;
}
#p2 {
position: absolute;
top: 0px;
left: 200px;
}
The div stays at the same place in the window when scrolling, p1 is in normal flow in Arial and red, and p2 is placed 0 px from the top and 200 px from the left of the page.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2076 · 5 marks
What is HTTP protocol? Define HTTP Request and Response.
Answer
HTTP protocol
HTTP (HyperText Transfer Protocol) is an application-layer protocol used by the World Wide Web to transfer hypertext documents, images and other resources between a client (browser) and a web server. It follows the client-server request-response model, runs over TCP (default port 80; HTTPS uses TLS on port 443), and is stateless: each request is independent, and the server keeps no memory of earlier requests unless cookies or sessions are used. Versions include HTTP/1.0, 1.1 (persistent connections), 2 and 3.
HTTP request
A message sent by the client to ask for a resource. It has:
- Request line: method, URL path, and HTTP version, e.g.
GET /index.html HTTP/1.1. - Headers:
Host,User-Agent,Accept,Cookie,Content-Type. - A blank line.
- An optional body (for POST/PUT, e.g. form data).
Methods: GET (fetch), POST (submit data), PUT (update/replace), DELETE (remove), HEAD (headers only).
HTTP response
The message returned by the server. It has:
- Status line: version, status code and phrase, e.g.
HTTP/1.1 200 OK. - Headers:
Content-Type,Content-Length,Set-Cookie,Server. - A blank line.
- Body: the requested resource (HTML, JSON, image).
Status code classes: 1xx informational, 2xx success (200 OK), 3xx redirection (301, 302), 4xx client error (404 Not Found, 403 Forbidden), 5xx server error (500, 503).
Example: the browser sends GET /about.html HTTP/1.1 and the server replies HTTP/1.1 200 OK followed by the HTML of the page.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2076 · 5 marks
Create a HTML page with tags header, article and footer. Insert alink containing mail to [email protected] in the footer tag. Set the keywords “iost”, “csit” using Meta tag in the page.
Answer
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="keywords" content="iost, csit">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>IOST CSIT</title>
</head>
<body>
<header>
<h1>Institute of Science and Technology</h1>
<p>BSc CSIT Program</p>
</header>
<article>
<h2>About the Course</h2>
<p>The BSc CSIT is a four-year program of Tribhuvan University covering
programming, databases, networks and web technology.</p>
</article>
<footer>
<p>Contact us:
<a href="mailto:info@example.com">info@example.com</a>
</p>
</footer>
</body>
</html>
The <meta name="keywords" content="iost, csit"> tag inside <head> sets the keywords. The <header>, <article> and <footer> are HTML5 semantic elements, and the link with mailto: opens the visitor's default email program with the address filled in. (The email address in the question is hidden in the source, so info@example.com is used as a placeholder to be replaced by the required address.)
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2076 · 5 marks
How jQuery animate can be used to create custom animation? Write syntax with sample script.
Answer
The jQuery animate() method creates custom animations by gradually changing numeric CSS properties of the selected elements from their current value to the given target value over a period of time. Only numeric properties (width, height, left, top, opacity, margin, font-size) can be animated; colours need a plugin. Properties are written in camelCase (marginLeft). Relative values such as "+=50px" are supported, and multiple animate() calls on the same element are queued and run one after another.
Syntax
$(selector).animate({properties}, duration, easing, callback);
properties: object of CSS properties and target values.duration:"slow","fast"or milliseconds (default 400).easing:"swing"(default) or"linear".callback: function executed after the animation ends.
Sample script
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function () {
$("#btn").click(function () {
$("#box").animate({
left: "250px",
opacity: 0.5,
height: "+=50px",
width: "+=50px"
}, 1500, "swing", function () {
alert("Animation complete");
});
});
});
</script>
</head>
<body>
<button id="btn">Start</button>
<div id="box" style="background:orange;height:100px;width:100px;position:relative;"></div>
</body>
</html>
On clicking the button, the box moves 250 px to the right, becomes half transparent and grows by 50 px in each dimension within 1.5 seconds. The element must have position relative, absolute or fixed to animate left. Animation can be stopped using .stop().
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2076 · 5 marks
What is the use of JSON? How can you parse a JSON, illustrate with an example.
Answer
Use of JSON
JSON (JavaScript Object Notation) is a lightweight, text-based, language-independent format for storing and exchanging structured data. Its uses are:
- Data exchange between the client and the server (AJAX, REST APIs), as a lighter alternative to XML.
- Configuration files and storage of data (e.g.
package.json, NoSQL databases). - It is easy for humans to read and for machines to parse, and is supported by almost every language.
JSON consists of name/value pairs in {} (objects) and ordered lists in [] (arrays). Values may be string, number, boolean, null, object or array. Keys must be in double quotes.
Parsing JSON
Parsing means converting a JSON string into a JavaScript object using JSON.parse(). The reverse is JSON.stringify().
<!DOCTYPE html>
<html>
<body>
<p id="out"></p>
<script>
var text = '{"name":"Ram","age":21,"courses":["Web Tech","DBMS"]}';
var obj = JSON.parse(text); // string -> object
document.getElementById("out").innerHTML =
obj.name + " is " + obj.age + " years old and studies " +
obj.courses.join(", ");
var back = JSON.stringify(obj); // object -> string
</script>
</body>
</html>
Output: Ram is 21 years old and studies Web Tech, DBMS.
If the string is not valid JSON, JSON.parse() throws a SyntaxError, so it is placed in try...catch. In PHP the equivalent functions are json_decode() and json_encode().
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2076 · 5 marks
What is XML? Create an XML file containing records of employee having elements of simple and complex types.
Answer
XML
XML (eXtensible Markup Language) is a W3C markup language used to describe and transport data. Unlike HTML, tags are not predefined; the author creates his or her own tags, and the focus is on what the data is, not on how it is displayed. An XML document must be well formed: a single root element, every tag closed, correct nesting, case-sensitive names and quoted attribute values. XML is platform independent and is used for configuration, data exchange and web services.
Simple and complex elements
- A simple type element contains only text (no child elements or attributes), e.g.
<name>Ram</name>. - A complex type element contains child elements and/or attributes, e.g.
<address>with<city>and<street>.
employees.xml
<?xml version="1.0" encoding="UTF-8"?>
<employees>
<employee id="101">
<name>Ram Sharma</name>
<age>30</age>
<salary>45000</salary>
<address>
<city>Kathmandu</city>
<street>Baneshwor</street>
</address>
<phone>9841000001</phone>
</employee>
<employee id="102">
<name>Sita Thapa</name>
<age>27</age>
<salary>52000</salary>
<address>
<city>Pokhara</city>
<street>Lakeside</street>
</address>
<phone>9851000002</phone>
</employee>
</employees>
Here name, age, salary, city, street and phone are simple elements, while employees, employee (it has the attribute id and children) and address are complex elements.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2076 · 5 marks
How XSD of a XML file is created? Illustrate with an example.
Answer
XSD
XSD (XML Schema Definition) is a W3C language that defines the structure, elements, attributes, order and data types an XML document must have, so that the document can be validated. XSD is itself written in XML, supports data types (string, integer, decimal, date) and restrictions, and has replaced DTD for most uses.
Creating an XSD for an XML file
- Start with the
<xs:schema>root element and the namespacexmlns:xs="http://www.w3.org/2001/XMLSchema". - Declare the root element of the XML file using
<xs:element>. - For each simple element give a built-in type (
xs:string,xs:integer). - For an element with children, define a complexType with
<xs:sequence>(ordered),<xs:all>or<xs:choice>containing the child element declarations. - Declare attributes with
<xs:attribute>inside the complexType. - Use
minOccursandmaxOccursfor the number of occurrences, andxs:restrictionfor limits. - Link the schema in the XML document with
xsi:noNamespaceSchemaLocationand validate.
Example
XML file student.xml:
<?xml version="1.0"?>
<student xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="student.xsd" roll="5">
<name>Hari</name>
<age>21</age>
<email>hari@example.com</email>
</student>
Schema student.xsd:
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="student">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="age">
<xs:simpleType>
<xs:restriction base="xs:integer">
<xs:minInclusive value="16"/>
<xs:maxInclusive value="60"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
<xs:element name="email" type="xs:string" minOccurs="0"/>
</xs:sequence>
<xs:attribute name="roll" type="xs:integer" use="required"/>
</xs:complexType>
</xs:element>
</xs:schema>
A validator would reject the XML if, for example, age were text or outside 16-60, or if the roll attribute were missing.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2076 · 5 marks
How can you define variables in PHP? Define any two variable of string types and display their results after concatenation.
Answer
Defining variables in PHP
- A PHP variable starts with the
$sign followed by its name, e.g.$name. - The name starts with a letter or underscore, can contain letters, digits and underscores, and is case-sensitive (
$aand$Adiffer). - No type declaration is needed; PHP is loosely typed and the type is set by the value assigned with
=, e.g.$x = 5;(integer),$s = "Hi";(string),$f = 2.5;(float),$b = true;(boolean). - Variables have local, global, static or superglobal scope.
String variables and concatenation
PHP's concatenation operator is the dot (.).
<?php
$first = "Education";
$second = "Nepal";
$result = $first . " " . $second; // concatenation
echo "First string: $first <br>";
echo "Second string: $second <br>";
echo "After concatenation: " . $result;
?>
Output:
First string: Education
Second string: Nepal
After concatenation: Education Nepal
The shorthand .= appends to an existing string, e.g. $first .= " Site";.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2076 · 5 marks
How web pages can be made responsive using media queries ? Illustrate with an example.
Answer
Responsive web pages and media queries
A responsive page adapts its layout to the size of the device screen (mobile, tablet, desktop). Media queries are a CSS3 feature that applies a block of CSS rules only if the condition(s) about the device are true, such as the viewport width, height, orientation or resolution.
Syntax
@media media-type and (condition) {
selector { property: value; }
}
For example, @media screen and (max-width: 600px) { ... } applies the rules when the viewport width is 600 px or less. The conditions can be combined with and, , (or) and not.
The page must include the viewport meta tag so that mobile browsers do not scale the page down:
<meta name="viewport" content="width=device-width, initial-scale=1.0">
Other techniques that go with media queries are fluid widths in percentages, flexible images (max-width: 100%), flexbox and grid.
Example
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
.container { display: flex; }
.menu { width: 25%; background: lightblue; padding: 10px; }
.content { width: 75%; background: lightyellow; padding: 10px; }
/* Tablets and phones: stack columns */
@media screen and (max-width: 768px) {
.container { flex-direction: column; }
.menu, .content { width: 100%; }
}
/* Small phones */
@media screen and (max-width: 480px) {
body { font-size: 14px; }
.menu { display: none; }
}
</style>
</head>
<body>
<div class="container">
<div class="menu">Menu</div>
<div class="content">Main content</div>
</div>
</body>
</html>
On a wide screen the menu and content appear side by side (25% and 75%). Below 768 px they stack in one column, and below 480 px the menu is hidden and the font is smaller.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2076 · 5 marks
Why inline frames are used? Create a HTML page containing iframe within a paragraph. The iframe have source to http://www.tuiost.edu.np and its height and width are 200px and 400px respectively.
Answer
Why inline frames are used. An inline frame (<iframe>) embeds another HTML document inside the current page, in a rectangular region that can sit in the normal flow of text. It is used to:
- show content from another site or page (maps, videos, advertisements, widgets) without leaving the current page;
- load a separate document that has its own scrolling, styles and scripts, so it does not interfere with the host page;
- act as the target of links and forms (
target="frame-name"), so only the frame area refreshes; - keep a section independent, so it can be reloaded or replaced without reloading the whole page.
HTML page with an iframe inside a paragraph
<!DOCTYPE html>
<html>
<head>
<title>Inline Frame Example</title>
</head>
<body>
<p>
The Institute of Science and Technology website is shown below:
<iframe src="http://www.tuiost.edu.np" width="400px" height="200px">
Your browser does not support inline frames.
</iframe>
</p>
</body>
</html>
The src attribute gives the address of the page to embed, and width="400px" and height="200px" set its size. The text between the tags is shown only by browsers that do not support iframes.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2078 · 10 marks
How do you define an Array in PHP? write a PHP script to create a multidimensional array name Product that will contain pcode, pname. and price. Initialize the array with at least three instances. Also, Write an HTML script to display the initialized values of the array in an HTML Table.
Answer
Arrays in PHP. An array stores several values under one variable name. Each value is reached by a key (numeric index or string). An array is created with array(...) or the short syntax [...].
- Indexed array:
$colors = array("red", "green", "blue"); - Associative array:
$age = array("Ram" => 20, "Sita" => 22); - Multidimensional array: an array whose elements are themselves arrays.
(a) PHP script: multidimensional array Product
<?php
$Product = array(
array("pcode" => "P101", "pname" => "Keyboard", "price" => 1500),
array("pcode" => "P102", "pname" => "Mouse", "price" => 800),
array("pcode" => "P103", "pname" => "Monitor", "price" => 12000)
);
?>
(b) Displaying the values in an HTML table
<!DOCTYPE html>
<html>
<head><title>Product List</title></head>
<body>
<?php
$Product = array(
array("pcode" => "P101", "pname" => "Keyboard", "price" => 1500),
array("pcode" => "P102", "pname" => "Mouse", "price" => 800),
array("pcode" => "P103", "pname" => "Monitor", "price" => 12000)
);
?>
<table border="1" cellpadding="5">
<tr>
<th>Product Code</th>
<th>Product Name</th>
<th>Price (Rs)</th>
</tr>
<?php foreach ($Product as $item) { ?>
<tr>
<td><?php echo $item["pcode"]; ?></td>
<td><?php echo $item["pname"]; ?></td>
<td><?php echo $item["price"]; ?></td>
</tr>
<?php } ?>
</table>
</body>
</html>
The foreach loop visits each inner array, and each pass writes one table row, so the output has a header row and three data rows (P101 Keyboard 1500, P102 Mouse 800, P103 Monitor 12000).
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2078 · 10 marks
Create an HTML signup form with fields Name, Email, Password, and Age, Validate the form using JavaScript. Write functions for validating each of the elements. All of the fields should not be empty. The Email address should be a valid email, the password should be of length at least 6 and should start with the alphabet and end with a digit. The age should be between 8 and 60.
Answer
HTML signup form with JavaScript validation
<!DOCTYPE html>
<html>
<head>
<title>Signup Form</title>
<script>
function isEmpty(value) {
return value.trim() === "";
}
function validateName() {
var name = document.getElementById("name").value;
if (isEmpty(name)) { alert("Name must not be empty."); return false; }
return true;
}
function validateEmail() {
var email = document.getElementById("email").value;
if (isEmpty(email)) { alert("Email must not be empty."); return false; }
var pattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!pattern.test(email)) { alert("Enter a valid email address."); return false; }
return true;
}
function validatePassword() {
var pw = document.getElementById("password").value;
if (isEmpty(pw)) { alert("Password must not be empty."); return false; }
if (pw.length < 6) { alert("Password must be at least 6 characters long."); return false; }
if (!/^[A-Za-z]/.test(pw)) { alert("Password must start with an alphabet."); return false; }
if (!/[0-9]$/.test(pw)) { alert("Password must end with a digit."); return false; }
return true;
}
function validateAge() {
var age = document.getElementById("age").value;
if (isEmpty(age)) { alert("Age must not be empty."); return false; }
age = Number(age);
if (isNaN(age) || age < 8 || age > 60) { alert("Age must be between 8 and 60."); return false; }
return true;
}
function validateForm() {
return validateName() && validateEmail() && validatePassword() && validateAge();
}
</script>
</head>
<body>
<h2>Sign Up</h2>
<form name="signup" onsubmit="return validateForm()">
Name: <input type="text" id="name"><br><br>
Email: <input type="text" id="email"><br><br>
Password: <input type="password" id="password"><br><br>
Age: <input type="text" id="age"><br><br>
<input type="submit" value="Sign Up">
</form>
</body>
</html>
Explanation. Each field has its own function that returns true or false. validateForm() combines them with &&, so the form is submitted only if every check passes. onsubmit="return validateForm()" cancels submission when it returns false. The email check uses a regular expression for the form text@domain.ext. For the password, pw.length < 6 tests the length, ^[A-Za-z] tests that it starts with a letter and [0-9]$ tests that it ends with a digit. The age is converted with Number() and compared with the limits 8 and 60.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2078 · 10 marks
How external CSS is inserted in an HTML page? Create an HTML page with two paragraph tags With id pl and p2, and one div tag with id dv1. Write an external CSS file as per the description. the margin of the paragraphs should be 100px from the top and 80px from the left. Both of paragraphs should have the display set to block. The dv1 should have padding left and right set to 30px and 25px respectively, its background color should be blue and the font color should be red with the font type Verdana. Set the display of dv1 to none.
Answer
Inserting external CSS. An external style sheet is a separate .css file that holds the style rules. It is linked into the HTML page with a <link> tag placed inside <head>:
<link rel="stylesheet" type="text/css" href="style.css">
One style sheet can then style many pages, and changing the file changes all of them. (The @import rule inside a <style> block can also load an external file.)
HTML page (index.html)
<!DOCTYPE html>
<html>
<head>
<title>External CSS</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<p id="p1">This is the first paragraph.</p>
<p id="p2">This is the second paragraph.</p>
<div id="dv1">This is a div.</div>
</body>
</html>
External CSS file (style.css)
#p1, #p2 {
margin-top: 100px;
margin-left: 80px;
display: block;
}
#dv1 {
padding-left: 30px;
padding-right: 25px;
background-color: blue;
color: red;
font-family: Verdana, sans-serif;
display: none;
}
Both paragraphs get a top margin of 100px, a left margin of 80px and block display. The div dv1 has left and right padding of 30px and 25px, a blue background, red Verdana text, and display: none, so it is not shown on the page.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2078 · 5 marks
What are the services provided under web2.0?
Answer
Web 2.0 is the second generation of the web, where users do not only read content but also create, share and collaborate on it. It is also called the participative or social web. The main services provided under Web 2.0 are:
- Blogs: online journals where individuals publish posts and readers comment (WordPress, Blogger).
- Wikis: pages that many users can edit together (Wikipedia).
- Social networking: sites to connect, chat and share (Facebook, LinkedIn, Twitter/X).
- Media sharing: upload and share videos, photos and slides (YouTube, Flickr, SlideShare).
- Social bookmarking and tagging: saving, tagging and sharing links (Delicious, Pinterest).
- Podcasts and RSS feeds: audio or video series and syndicated updates delivered to subscribers.
- Web applications and cloud services: rich online applications built with AJAX, such as Google Docs and Gmail.
- Folksonomy and user reviews/ratings: user-made tags and ratings that organise content (Amazon reviews).
- Mashups: pages that combine data from several sources, such as a map overlaid with other data via APIs.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2078 · 5 marks
Create an HTML page with its body containing a div. The div should contain an image within
it. Create a link on the image to redirect to the url http://www.tuiost.edu.np. Set the title of the
page to “iost”. Add Meta tag on the page.
Answer
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="description" content="Institute of Science and Technology, Tribhuvan University">
<meta name="keywords" content="iost, tribhuvan university, HTML">
<meta name="author" content="Student">
<title>iost</title>
</head>
<body>
<div>
<a href="http://www.tuiost.edu.np">
<img src="iost.jpg" alt="IOST logo" width="200" height="150">
</a>
</div>
</body>
</html>
The <title> tag sets the page title to "iost". The <meta> tags inside <head> give information about the page (character set, description, keywords, author) and are not displayed. The <img> is placed inside an <a> tag within the <div>, so clicking the image takes the user to http://www.tuiost.edu.np.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2078 · 5 marks
How jQuery id selector can be used to select specific element? Write an example with jQuery
that will hide a paragraph on clicking a button.
Answer
jQuery id selector. The id selector uses the # symbol followed by the id of the element, written inside $(): $("#id"). It selects the single element with that id (an id must be unique on a page), and jQuery methods such as hide(), show() or css() can then be applied to it.
Example: hide a paragraph when a button is clicked
<!DOCTYPE html>
<html>
<head>
<title>jQuery id selector</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function () {
$("#btn").click(function () {
$("#para").hide();
});
});
</script>
</head>
<body>
<p id="para">This paragraph will be hidden when the button is clicked.</p>
<button id="btn">Hide Paragraph</button>
</body>
</html>
When the page is ready, a click handler is attached to the button selected by #btn. On a click, $("#para") selects the paragraph with id para and hide() removes it from view.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2078 · 5 marks
Create a HTML page containing ordered and unordered lists. Set the value of ordered list type
to “A”. The list should start at “D”.
Answer
<!DOCTYPE html>
<html>
<head>
<title>Lists</title>
</head>
<body>
<h3>Ordered List (type A, starting at D)</h3>
<ol type="A" start="4">
<li>HTML</li>
<li>CSS</li>
<li>JavaScript</li>
</ol>
<h3>Unordered List</h3>
<ul>
<li>PHP</li>
<li>XML</li>
<li>jQuery</li>
</ul>
</body>
</html>
type="A" makes the ordered list use capital letters. The start attribute always takes a number, so the letter D (the 4th letter) is written as start="4". The list therefore shows D. HTML, E. CSS, F. JavaScript. The <ul> list shows the default bullet markers.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2078 · 5 marks
Discuss about different JSON data types.
Answer
JSON (JavaScript Object Notation) is a lightweight text format for exchanging data, built from name/value pairs and ordered lists of values. A JSON value can be one of the following types.
- String: text in double quotes, e.g.
"name": "Ram". - Number: an integer or floating-point value without quotes, e.g.
"age": 21,"marks": 85.5. - Boolean:
trueorfalse, e.g."passed": true. - Null: an empty value, written
null, e.g."middleName": null. - Object: an unordered collection of name/value pairs inside
{ }, e.g."address": {"city": "Kathmandu", "ward": 5}. - Array: an ordered list of values inside
[ ], e.g."subjects": ["Web Tech", "AI", "DBMS"].
Example combining all types:
{
"name": "Ram",
"age": 21,
"passed": true,
"middleName": null,
"address": { "city": "Kathmandu", "ward": 5 },
"subjects": ["Web Tech", "AI", "DBMS"]
}
Keys must be strings in double quotes. Functions, dates and undefined are not JSON types.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2078 · 5 marks
What is DTD? Create a XML file and write its equivalent DTD.
Answer
DTD (Document Type Definition). A DTD defines the structure and the legal elements and attributes of an XML document. It lists which elements may appear, in what order, how many times, and what they contain. An XML document that follows its DTD is called valid. A DTD can be written inside the XML file (internal) or in a separate .dtd file (external).
XML file (student.xml)
<?xml version="1.0"?>
<!DOCTYPE student SYSTEM "student.dtd">
<student>
<name>Ram Sharma</name>
<roll>101</roll>
<course>BSc CSIT</course>
</student>
Equivalent DTD (student.dtd)
<!ELEMENT student (name, roll, course)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT roll (#PCDATA)>
<!ELEMENT course (#PCDATA)>
<!ELEMENT student (name, roll, course)> says the root element student must contain name, roll and course in that order. #PCDATA means the element holds parsed text.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2078 · 5 marks
How can you define function in PHP? Create a function that will take two integers as argument and will return product of them.
Answer
Defining a function in PHP. A function is a named block of code that runs when called. It is defined with the function keyword, a name, a parameter list in parentheses and a body in braces. return sends a value back to the caller.
function functionName($param1, $param2) {
// statements
return $value;
}
Function that returns the product of two integers
<?php
function product($a, $b) {
return $a * $b;
}
echo "Product = " . product(6, 7); // Product = 42
?>
The call product(6, 7) passes 6 and 7 as arguments, the function returns , and echo prints it.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2078 · 5 marks
Describe CSS Box model with example.
Answer
CSS box model. Every HTML element is treated as a rectangular box. The box model describes the layers of this box, from the inside out:
- Content: the text or image itself; its size is set by
widthandheight. - Padding: transparent space between the content and the border.
- Border: a line drawn around the padding and content.
- Margin: transparent space outside the border that separates the element from its neighbours.
+---------------------------+
| Margin |
| +---------------------+ |
| | Border | |
| | +---------------+ | |
| | | Padding | | |
| | | +---------+ | | |
| | | | Content | | | |
| | | +---------+ | | |
| | +---------------+ | |
| +---------------------+ |
+---------------------------+
Example
<style>
div {
width: 200px;
padding: 20px;
border: 5px solid black;
margin: 30px;
}
</style>
<div>Box model example</div>
Total width taken by the box px (content + padding + border + margin on both sides). The visible box (without margin) is px wide. With box-sizing: border-box, the width includes padding and border instead.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 10 marks
What is the use of XML?Create a XML file with simple type and complex type elements. Write its equivalent DTD.
Answer
Use of XML. XML (eXtensible Markup Language) is a markup language for storing and transporting data. Its uses are:
- describing and exchanging data between different systems and platforms in a plain-text, software-independent form;
- separating data from presentation, since XML only describes the data (HTML shows it);
- storing configuration and structured documents (e.g. RSS feeds, SVG, Office file formats);
- building new markup languages, because the user defines their own tags;
- web services (SOAP) and data sharing between applications.
XML file (book.xml)
A simple-type element contains only text; a complex-type element contains other elements or attributes.
<?xml version="1.0"?>
<!DOCTYPE library SYSTEM "library.dtd">
<library>
<book id="b1">
<title>Web Technology</title>
<author>Ram Sharma</author>
<price>550</price>
</book>
</library>
Here title, author and price are simple elements (text only). book and library are complex elements (they contain child elements, and book also has an attribute).
Equivalent DTD (library.dtd)
<!ELEMENT library (book+)>
<!ELEMENT book (title, author, price)>
<!ATTLIST book id CDATA #REQUIRED>
<!ELEMENT title (#PCDATA)>
<!ELEMENT author (#PCDATA)>
<!ELEMENT price (#PCDATA)>
book+ means one or more book elements are allowed. #REQUIRED means the id attribute must be present.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 10 marks
Create an HTML file containing form elements textbox for username, password field and a checkbox for hobbies. Now write javascript function for the form validation. You should validate for username to be empty, password should be of length at least 5, and the check box should be checked.
Answer
<!DOCTYPE html>
<html>
<head>
<title>Form Validation</title>
<script>
function validateForm() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
var hobbies = document.getElementsByName("hobby");
// 1. username must not be empty
if (username.trim() === "") {
alert("Username must not be empty.");
return false;
}
// 2. password length at least 5
if (password.length < 5) {
alert("Password must be at least 5 characters long.");
return false;
}
// 3. at least one hobby checked
var checked = false;
for (var i = 0; i < hobbies.length; i++) {
if (hobbies[i].checked) { checked = true; break; }
}
if (!checked) {
alert("Please select at least one hobby.");
return false;
}
return true;
}
</script>
</head>
<body>
<form onsubmit="return validateForm()">
Username: <input type="text" id="username"><br><br>
Password: <input type="password" id="password"><br><br>
Hobbies:
<input type="checkbox" name="hobby" value="reading"> Reading
<input type="checkbox" name="hobby" value="music"> Music
<input type="checkbox" name="hobby" value="sports"> Sports<br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
The function is called when the form is submitted. If any check fails it shows a message and returns false, which stops the submission. If all three checks pass it returns true and the form is submitted.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 10 marks
How database connection is created in PHP? Write a PHP program to create a form and insert values in to the database table. The form should contain at least two input fields.
Answer
Creating a database connection in PHP. PHP connects to MySQL using the mysqli extension (or PDO):
- Call
mysqli_connect(host, username, password, database)(ornew mysqli(...)) to open the connection. - Check the result and stop with an error message if it failed.
- Run SQL with
mysqli_query($conn, $sql). - Close the connection with
mysqli_close($conn).
Form and insert program (student.php)
Assume a database college with the table:
CREATE TABLE student (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50),
email VARCHAR(50)
);
<!DOCTYPE html>
<html>
<head><title>Insert Student</title></head>
<body>
<form method="post" action="">
Name: <input type="text" name="name"><br><br>
Email: <input type="text" name="email"><br><br>
<input type="submit" name="submit" value="Save">
</form>
<?php
if (isset($_POST['submit'])) {
$conn = mysqli_connect("localhost", "root", "", "college");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$name = mysqli_real_escape_string($conn, $_POST['name']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$sql = "INSERT INTO student (name, email) VALUES ('$name', '$email')";
if (mysqli_query($conn, $sql)) {
echo "Record inserted successfully.";
} else {
echo "Error: " . mysqli_error($conn);
}
mysqli_close($conn);
}
?>
</body>
</html>
When the form is posted, the script opens the connection to the college database, escapes the submitted values to prevent SQL injection, runs the INSERT statement, reports the result and closes the connection.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 5 marks
Differentiate Web 1.0 from Web 2.0.
Answer
| Basis | Web 1.0 | Web 2.0 |
|---|---|---|
| Nature | Read-only web; users only view content | Read-write web; users create and share content |
| Content creation | By a few webmasters/publishers | By ordinary users (blogs, wikis, posts) |
| Interaction | Little or none | Highly interactive and social |
| Pages | Mostly static HTML | Dynamic pages using AJAX, JavaScript, CSS |
| Examples | Early company brochure sites, directories | Facebook, YouTube, Wikipedia, blogs |
| Technology | HTML, basic forms, frames | AJAX, RSS, XML, web services, APIs |
| Sharing | Content is owned by the site | Content is shared and tagged by users (folksonomy) |
| Software model | Software installed on the desktop | Web applications on the cloud (Google Docs) |
| Pricing/access | Pay for content or ads, e.g. Britannica | Free collaborative content, e.g. Wikipedia |
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 5 marks
Write a HTML script to generate following list of items;
-
Coffee : I. Black coffee II. Green coffee
-
Tea A: Black tea B. Green tea
Answer
The outer list is an ordered list with numbers (1, 2). The inner lists use Roman numerals (I, II) under Coffee and capital letters (A, B) under Tea.
<!DOCTYPE html>
<html>
<head>
<title>List of Items</title>
</head>
<body>
<ol type="1">
<li>Coffee
<ol type="I">
<li>Black coffee</li>
<li>Green coffee</li>
</ol>
</li>
<li>Tea
<ol type="A">
<li>Black tea</li>
<li>Green tea</li>
</ol>
</li>
</ol>
</body>
</html>
The nested <ol> is placed inside the <li> of its parent item, and the type attribute chooses the marker style: 1 for numbers, I for upper-case Roman numerals and A for upper-case letters.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 5 marks
Create a HTML page containing a div having id “dv1”. The div should contain canvas element. The id of canvas should be “mycanvas”. The height and width of canvas should be 200 and 300.
Answer
<!DOCTYPE html>
<html>
<head>
<title>Canvas</title>
</head>
<body>
<div id="dv1">
<canvas id="mycanvas" width="300" height="200"
style="border:1px solid #000000;">
Your browser does not support the canvas element.
</canvas>
</div>
</body>
</html>
The <canvas> element is a drawing area for graphics created with JavaScript. Here the width is 300 and the height is 200 (pixels). The text inside the tag is the fallback for old browsers, and the border is only to make the canvas visible.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 5 marks
What are the usages of class and id selectors in CSS? Illustrate with example.
Answer
Class selector. A class selector starts with a dot (.) followed by the class name. It selects every element that has that class, so the same style can be reused on many elements. An element can have several classes.
Id selector. An id selector starts with a hash (#) followed by the id. It selects the one element with that id; an id must be unique in the page. It is used for a single, specific element.
| Class selector | Id selector |
|---|---|
.name | #name |
| Can be used on many elements | Used on only one element |
| Lower specificity | Higher specificity |
Example
<!DOCTYPE html>
<html>
<head>
<style>
.note { color: blue; font-size: 18px; }
#main { background-color: yellow; font-weight: bold; }
</style>
</head>
<body>
<p class="note">First note (class).</p>
<p class="note">Second note (class).</p>
<p id="main">Main paragraph (id).</p>
</body>
</html>
Both paragraphs with class="note" are blue and 18px. Only the paragraph with id="main" has a yellow background and bold text.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 5 marks
What is word-wrap property in CSS? Write an HTML script to illustrate the word-wrap property.
Answer
word-wrap property. The CSS word-wrap property (now an alias of overflow-wrap) controls whether a long word that does not fit in its container may be broken and wrapped onto the next line.
normal: words break only at normal break points, so a long word may overflow the box.break-word: a long word may be broken at any point to stay inside the container.
Illustration
<!DOCTYPE html>
<html>
<head>
<style>
div {
width: 150px;
border: 1px solid black;
margin-bottom: 15px;
}
.normal { word-wrap: normal; }
.wrap { word-wrap: break-word; }
</style>
</head>
<body>
<p>word-wrap: normal</p>
<div class="normal">
Thisisaveryveryverylongwordwithoutanyspacesthatoverflows.
</div>
<p>word-wrap: break-word</p>
<div class="wrap">
Thisisaveryveryverylongwordwithoutanyspacesthatiswrapped.
</div>
</body>
</html>
In the first box the long word runs past the 150px border. In the second box it is broken and continues on the following lines inside the box.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 5 marks
Describe the jQuery Animate() method. Write an html script to create a div with id “mydiv”. The position of the div should be set to absolute. Now show the use of animate method to the div element to right by 300px.
Answer
jQuery animate() method. The animate() method creates custom animations by gradually changing numeric CSS properties of the selected elements.
Syntax:
$(selector).animate({styles}, speed, easing, callback);
styles(required): the CSS properties and target values, e.g.{left: '300px', opacity: 0.5}.speed(optional): duration in milliseconds, or"slow"/"fast".easing(optional):"swing"(default) or"linear".callback(optional): a function run after the animation ends.
Only numeric properties can be animated, and an element must have position set to relative, fixed or absolute for left/top animation to take effect.
Example
<!DOCTYPE html>
<html>
<head>
<title>animate()</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function () {
$("button").click(function () {
$("#mydiv").animate({ left: "300px" }, 1000);
});
});
</script>
<style>
#mydiv {
position: absolute;
left: 0;
width: 100px;
height: 100px;
background-color: orange;
}
</style>
</head>
<body>
<button>Move Right</button>
<div id="mydiv"></div>
</body>
</html>
The div has position: absolute. When the button is clicked, animate({left: "300px"}, 1000) moves it smoothly to 300px from the left over one second.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 5 marks
What is XML Namespace? How it is used to avoid element name conflict in XML? Justify with an example.
Answer
XML namespace. An XML namespace is a collection of element and attribute names identified by a unique URI. It is declared with the xmlns attribute and is used to give names a unique meaning, so that elements from different XML vocabularies can be combined without confusion.
Avoiding name conflicts. Because users invent their own tags, two documents may use the same tag name for different things. For example, <table> may mean an HTML table in one document and a piece of furniture in another. When the documents are merged, the parser cannot tell them apart. A namespace prefix solves this: each name is qualified by the prefix bound to its namespace URI.
Syntax: xmlns:prefix="URI". The URI is only an identifier and need not point to a real page.
Example
<?xml version="1.0"?>
<root xmlns:h="http://www.w3.org/TR/html4/"
xmlns:f="https://www.example.com/furniture">
<h:table>
<h:tr>
<h:td>Apples</h:td>
<h:td>Bananas</h:td>
</h:tr>
</h:table>
<f:table>
<f:name>African Coffee Table</f:name>
<f:width>80</f:width>
<f:length>120</f:length>
</f:table>
</root>
Here h:table belongs to the HTML namespace and f:table to the furniture namespace. Although both have the local name table, their qualified names differ, so there is no conflict and each can be processed according to its own definition.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 5 marks
How can you define class and objects in PHP? Write a PHP script to create class and its object.
Answer
Classes and objects in PHP. A class is a blueprint that groups properties (variables) and methods (functions). It is defined with the class keyword. An object is an instance of the class, created with the new keyword. Members are accessed with the arrow ->, and $this refers to the current object inside the class.
<?php
class Student {
public $name;
public $roll;
public function __construct($name, $roll) {
$this->name = $name;
$this->roll = $roll;
}
public function display() {
echo "Name: " . $this->name . ", Roll: " . $this->roll;
}
}
$s1 = new Student("Ram", 101); // create object
$s1->display(); // Name: Ram, Roll: 101
?>
Student is the class with two properties and a constructor __construct() that runs automatically when an object is created. $s1 is an object of the class, and $s1->display() calls its method.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 5 marks
How can you define array in PHP? Write a PHP function to create an array of type integer and print its elements.
Answer
Arrays in PHP. An array holds multiple values in a single variable. It is created with array() or [], and PHP supports indexed arrays (numeric keys), associative arrays (named keys) and multidimensional arrays. Elements are accessed by key, e.g. $a[0].
Function to create an integer array and print its elements
<?php
function showArray() {
$numbers = array(10, 20, 30, 40, 50); // array of integers
for ($i = 0; $i < count($numbers); $i++) {
echo $numbers[$i] . "<br>";
}
}
showArray();
?>
Output:
10
20
30
40
50
count($numbers) returns the number of elements (5), and the for loop prints each element by its index. A foreach ($numbers as $n) loop would give the same result.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 10 marks
How XML is different from HTML? Write XML script to create XML document containing element Person having sub elements Age, Name and Pincode. Write equivalent XSD for validating restrictions on the elements as the Age should be between 10 and 20, the Name should be only accepting either Ram or Shyam and the pincode should be 3 digit.
Answer
Difference between XML and HTML
| XML | HTML |
|---|---|
| eXtensible Markup Language | HyperText Markup Language |
| Designed to store and transport data | Designed to display data |
| Tags are user-defined | Tags are predefined |
| Case sensitive | Not case sensitive |
| Every tag must be closed | Some tags need not be closed (<br>) |
| Must be well formed; one root element | Errors are tolerated by browsers |
| Whitespace is preserved | Whitespace is collapsed |
| Focuses on what the data is | Focuses on how the data looks |
XML document (person.xml)
<?xml version="1.0" encoding="UTF-8"?>
<Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="person.xsd">
<Age>15</Age>
<Name>Ram</Name>
<Pincode>123</Pincode>
</Person>
Equivalent XSD (person.xsd)
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="Person">
<xs:complexType>
<xs:sequence>
<xs:element name="Age">
<xs:simpleType>
<xs:restriction base="xs:integer">
<xs:minInclusive value="10"/>
<xs:maxInclusive value="20"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
<xs:element name="Name">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:enumeration value="Ram"/>
<xs:enumeration value="Shyam"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
<xs:element name="Pincode">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:pattern value="[0-9]{3}"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
Explanation. Person is a complex element containing Age, Name and Pincode in sequence. Age is an integer restricted by minInclusive 10 and maxInclusive 20. Name is a string restricted by two enumeration values, so only Ram or Shyam is accepted. Pincode uses a pattern of [0-9]{3}, i.e. exactly three digits. The sample document (Age 15, Name Ram, Pincode 123) satisfies all restrictions.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 10 marks
Write a server side script in PHP to illustrate inserting and selecting values to and from database table. Create required connection using your own assumptions.
Answer
(a) Setup. Assume a MySQL database college with a table students:
CREATE DATABASE college;
USE college;
CREATE TABLE students (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
email VARCHAR(80) NOT NULL,
semester INT NOT NULL
);
(b) Connection, insert and select (PHP with MySQLi).
<?php
// connection settings (assumed)
$host = "localhost";
$user = "root";
$pass = "";
$db = "college";
$conn = new mysqli($host, $user, $pass, $db);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// ---- INSERT using a prepared statement ----
$name = "Ram Sharma";
$email = "ram@example.com";
$semester = 5;
$stmt = $conn->prepare("INSERT INTO students (name, email, semester) VALUES (?, ?, ?)");
$stmt->bind_param("ssi", $name, $email, $semester);
if ($stmt->execute()) {
echo "New record inserted. ID = " . $conn->insert_id . "<br>";
} else {
echo "Insert error: " . $stmt->error . "<br>";
}
$stmt->close();
// ---- SELECT ----
$result = $conn->query("SELECT id, name, email, semester FROM students");
if ($result->num_rows > 0) {
echo "<table border='1'><tr><th>ID</th><th>Name</th><th>Email</th><th>Semester</th></tr>";
while ($row = $result->fetch_assoc()) {
echo "<tr><td>{$row['id']}</td><td>{$row['name']}</td><td>{$row['email']}</td><td>{$row['semester']}</td></tr>";
}
echo "</table>";
} else {
echo "No records found.";
}
$conn->close();
?>
(c) Explanation. new mysqli(...) opens the connection; prepare/bind_param/execute insert the values safely (protecting against SQL injection); query runs the SELECT and fetch_assoc() returns each row as an associative array, which is printed in an HTML table. Finally the connection is closed.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 5 marks
Describe the WWW, web client and web server.
Answer
World Wide Web (WWW). The WWW is a global system of interlinked hypertext documents and resources (web pages, images, videos) stored on servers connected through the Internet. Each resource is identified by a URL, transferred using HTTP/HTTPS, and written mainly in HTML. It was proposed by Tim Berners-Lee in 1989 at CERN. The Web is a service running on the Internet, not the Internet itself.
Web client. A web client is the program (normally a web browser such as Chrome, Firefox or Edge) used by the user to request web resources. It sends an HTTP request to a server, receives the response, and renders HTML, CSS and JavaScript into the page the user sees. It also runs client-side scripts and stores cookies.
Web server. A web server is software (Apache, Nginx, IIS) running on a computer that stores web content and answers HTTP requests from clients. It locates the requested file, or runs a server-side script (PHP, ASP, Node.js) that may query a database, and sends back an HTTP response containing the page and a status code (e.g. 200 OK, 404 Not Found).
Working together. The user enters a URL; the browser resolves it using DNS, sends an HTTP request to the web server; the server processes it and returns the response; the browser displays it.
Web client (browser) --HTTP request--> Web server
Web client (browser) <--HTTP response-- Web server
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 5 marks
What are HTML keyboard events? Write a script to display a message “Hello world” on keypress event.
Answer
HTML keyboard events. These are events fired when the user interacts with the keyboard. The main ones are:
onkeydown: fires when a key is pressed down (repeats if held).onkeypress: fires when a key that produces a character is pressed (deprecated in modern browsers but still used in syllabus).onkeyup: fires when a key is released.
They can be attached to elements such as input fields or to the whole document/window, and the event object gives the key (event.key, event.keyCode).
Script to display "Hello world" on keypress.
<!DOCTYPE html>
<html>
<head>
<title>Keypress Event</title>
<script>
function showMessage() {
document.getElementById("msg").innerHTML = "Hello world";
alert("Hello world");
}
</script>
</head>
<body>
<p>Type something in the box:</p>
<input type="text" onkeypress="showMessage()">
<p id="msg"></p>
</body>
</html>
Whenever a key is pressed inside the textbox, showMessage() runs and "Hello world" is displayed.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 5 marks
How HTML elements are accessed using getElementById and getElementByTagName, illustrate using HTML script.
Answer
JavaScript accesses HTML elements through the DOM (Document Object Model) using methods of the document object.
getElementById(). Returns the single element whose id attribute matches. IDs are unique, so the result is one element (or null).
getElementsByTagName(). Returns a live collection (HTMLCollection) of all elements with the given tag name, accessed by index. (The correct method name has "Elements", i.e. getElementsByTagName.)
<!DOCTYPE html>
<html>
<head>
<title>DOM Access</title>
<script>
function useId() {
var el = document.getElementById("title");
el.style.color = "red";
el.innerHTML = "Changed using getElementById";
}
function useTag() {
var items = document.getElementsByTagName("p");
for (var i = 0; i < items.length; i++) {
items[i].style.backgroundColor = "yellow";
}
alert("Number of paragraphs: " + items.length);
}
</script>
</head>
<body>
<h2 id="title">Original Heading</h2>
<p>Paragraph one</p>
<p>Paragraph two</p>
<p>Paragraph three</p>
<button onclick="useId()">By Id</button>
<button onclick="useTag()">By Tag Name</button>
</body>
</html>
Clicking By Id changes only the heading with id title; clicking By Tag Name collects all three <p> elements and highlights each.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 5 marks
How can you define position property for specifying specific positioning of an HTML element? Write internal CSS to illustrate position of an HTML div.
Answer
CSS position property. The position property decides how an element is placed in the page, together with the offset properties top, right, bottom, left. Its values are:
static: default; element follows the normal flow, offsets have no effect.relative: positioned relative to its normal position; the original space is kept.absolute: removed from the flow and positioned relative to the nearest positioned ancestor (or the page).fixed: positioned relative to the browser viewport and stays in place while scrolling.sticky: behaves as relative until a scroll threshold is reached, then sticks like fixed.
z-index controls stacking order of overlapping positioned elements.
Internal CSS example.
<!DOCTYPE html>
<html>
<head>
<style>
#container {
position: relative;
width: 400px;
height: 250px;
border: 2px solid black;
}
#box {
position: absolute;
top: 50px;
left: 100px;
width: 150px;
height: 80px;
background-color: lightblue;
border: 1px solid blue;
}
</style>
</head>
<body>
<div id="container">
<div id="box">Positioned div</div>
</div>
</body>
</html>
The inner div is absolutely positioned 50px from the top and 100px from the left of its relatively positioned parent container.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 5 marks
What is chaining in jQuery? Write a script to illustrate concept of chaining using slideUp and slideDown method.
Answer
Chaining in jQuery. Chaining means running several jQuery methods one after another on the same selected element(s) in a single statement. Each jQuery method returns the jQuery object, so the next method can be attached with a dot. This avoids re-selecting the element, makes code shorter and faster.
Syntax: $("selector").method1().method2().method3();
Script using slideUp and slideDown.
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function () {
$("#btn").click(function () {
$("#panel").slideUp(1000).slideDown(1000).css("background-color", "lightgreen");
});
});
</script>
<style>
#panel { width: 300px; height: 100px; background: lightblue; padding: 10px; }
</style>
</head>
<body>
<button id="btn">Run chain</button>
<div id="panel">Chaining demo</div>
</body>
</html>
On clicking the button, the div first slides up (hides) over 1 second, then slides down (shows) over 1 second, and finally its background colour changes to light green, all in one chained statement on $("#panel").
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 5 marks
What is XML? Why is it called extensible? Mention the use of XML.
Answer
XML. XML (eXtensible Markup Language) is a W3C-recommended markup language for describing, storing and transporting data in a structured, human- and machine-readable text format. Unlike HTML, which displays data, XML describes what the data is. Tags are not predefined; the author defines them.
Example:
<student>
<name>Sita</name>
<roll>12</roll>
</student>
Why "extensible". It is called extensible because there is no fixed set of tags: users can create their own tags and structures to suit their data, and can extend or modify a vocabulary (using DTD or XML Schema) without breaking existing applications. New elements can be added later while older software still reads the unchanged parts.
Uses of XML.
- Exchange of data between different systems and platforms (web services, SOAP, RSS feeds).
- Storing configuration data (e.g. Android manifest, web.xml).
- Separating data from presentation, with XSLT/CSS used to display it.
- Data storage as a simple text-based database alternative.
- Defining other languages (XHTML, SVG, MathML) and document formats (docx, xlsx are zipped XML).
- Used in AJAX responses and in data sharing between organisations.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 5 marks
What is XMLHttpRequest object? Write HTML script with AJAX showing the use of XMLHttpRequest object.
Answer
XMLHttpRequest object. XMLHttpRequest (XHR) is a built-in browser JavaScript object used to exchange data with a web server in the background, without reloading the whole page. It is the core of AJAX. It can send requests (GET/POST) and receive text, XML or JSON.
Main members:
open(method, url, async): prepares the request.send()/send(data): sends it.onreadystatechange: handler called when state changes.readyState: 0 to 4 (4 = done);status: 200 means OK.responseText/responseXML: server response.
HTML script using AJAX.
<!DOCTYPE html>
<html>
<head>
<script>
function loadData() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById("result").innerHTML = xhr.responseText;
}
};
xhr.open("GET", "info.txt", true);
xhr.send();
}
</script>
</head>
<body>
<div id="result">Content will appear here.</div>
<button onclick="loadData()">Load Data</button>
</body>
</html>
When the button is clicked, the browser asynchronously requests info.txt; when the response arrives successfully, only the result div is updated and the page is not reloaded.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 5 marks
Write a PHP program that includes a function that will take two strings as input argument and print concatenation of two strings.
Answer
<?php
function concatStrings($a, $b) {
$result = $a . $b;
echo "Concatenated string: " . $result;
}
concatStrings("Hello ", "World");
?>
Output:
Concatenated string: Hello World
The function concatStrings takes two string arguments and joins them using PHP's concatenation operator . (dot), then prints the result with echo. A call such as concatStrings("Web ", "Technology") would print Web Technology.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 5 marks
How can you handle session in PHP?
Answer
Session in PHP. HTTP is stateless, so a session is used to store user data (e.g. login information) on the server across multiple pages. PHP creates a unique session ID for each visitor, stores it on the client in a cookie (PHPSESSID), and keeps the data in a file on the server. Session data is stored in the superglobal array $_SESSION.
Steps to handle sessions.
- Start a session with
session_start(). It must be called before any output is sent. - Set session variables in
$_SESSION. - Read them on any page after calling
session_start(). - Modify or remove variables with
unset(). - Destroy the session with
session_destroy().
<?php
// page1.php
session_start();
$_SESSION["username"] = "Ram";
$_SESSION["role"] = "student";
echo "Session variables set.";
?>
<?php
// page2.php
session_start();
echo "Welcome " . $_SESSION["username"]; // Welcome Ram
unset($_SESSION["role"]); // remove one variable
?>
<?php
// logout.php
session_start();
session_unset(); // remove all variables
session_destroy(); // destroy the session
echo "Logged out.";
?>
Sessions are more secure than cookies because the data stays on the server and only the session ID is sent to the browser. The session ends when destroyed, or when the browser closes or the timeout expires.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 10 marks
Describe the rules for creating XML document. Create a XML file with simple type and elements with attribute and nested elements. Write its equivalent XSD.
Answer
(a) Rules for creating an XML document.
- An XML document must have exactly one root element that contains all other elements.
- Every start tag must have a matching end tag (or be self-closed, e.g.
<br/>). - Elements must be properly nested; tags cannot overlap.
- XML is case sensitive:
<Name>and<name>are different. - Attribute values must always be enclosed in quotes.
- Names must start with a letter or underscore, contain no spaces, and not start with
xml. - Special characters must be written as entities (
<,>,&,",'). - An optional XML declaration may appear first:
<?xml version="1.0" encoding="UTF-8"?>. - Comments use
<!-- ... -->.
(b) XML file (simple elements, attribute, nested elements).
<?xml version="1.0" encoding="UTF-8"?>
<students>
<student id="1">
<name>Ram Sharma</name>
<age>21</age>
<address>
<city>Kathmandu</city>
<district>Kathmandu</district>
</address>
</student>
<student id="2">
<name>Sita Thapa</name>
<age>20</age>
<address>
<city>Pokhara</city>
<district>Kaski</district>
</address>
</student>
</students>
(c) Equivalent XSD.
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="students">
<xs:complexType>
<xs:sequence>
<xs:element name="student" maxOccurs="unbounded">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="age" type="xs:integer"/>
<xs:element name="address">
<xs:complexType>
<xs:sequence>
<xs:element name="city" type="xs:string"/>
<xs:element name="district" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="id" type="xs:integer" use="required"/>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
The schema defines name, age, city and district as simple-type elements, student and address as complex types with nested child elements, and id as an attribute of student.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 10 marks
Create an HTML file containing form with textbox, select and radio button. Now write a javascript function for validating the form elements. Validate textbox for required, select field should have some value selected and radio button should be checked.
Answer
<!DOCTYPE html>
<html>
<head>
<title>Form Validation</title>
<script>
function validateForm() {
var name = document.forms["myForm"]["fname"].value;
var course = document.forms["myForm"]["course"].value;
var genders = document.forms["myForm"]["gender"];
var checked = false;
if (name.trim() == "") {
alert("Name is required");
return false;
}
if (course == "") {
alert("Please select a course");
return false;
}
for (var i = 0; i < genders.length; i++) {
if (genders[i].checked) { checked = true; break; }
}
if (!checked) {
alert("Please select a gender");
return false;
}
alert("Form submitted successfully");
return true;
}
</script>
</head>
<body>
<form name="myForm" onsubmit="return validateForm()">
Name: <input type="text" name="fname"><br><br>
Course:
<select name="course">
<option value="">-- Select --</option>
<option value="csit">BSc CSIT</option>
<option value="bca">BCA</option>
<option value="bit">BIT</option>
</select><br><br>
Gender:
<input type="radio" name="gender" value="male"> Male
<input type="radio" name="gender" value="female"> Female
<input type="radio" name="gender" value="other"> Other<br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Explanation. On submit, validateForm() runs. The textbox is required, so an empty (or blank) value shows an alert. The select field's default option has value "", so choosing nothing is detected. Radio buttons share one name and form a collection; the loop checks whether any has checked set. Returning false stops the form from being submitted.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 10 marks
Write a PHP program to create a form. Create an insertdb() method to insert the form vlaues into a database table and display() to display the database table value.
Answer
Assume MySQL database college with table:
CREATE TABLE student (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50),
email VARCHAR(80),
phone VARCHAR(15)
);
PHP program (form.php).
<?php
function connect() {
$conn = new mysqli("localhost", "root", "", "college");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
return $conn;
}
function insertdb($name, $email, $phone) {
$conn = connect();
$stmt = $conn->prepare("INSERT INTO student (name, email, phone) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $name, $email, $phone);
if ($stmt->execute()) {
echo "<p>Record inserted successfully.</p>";
} else {
echo "<p>Error: " . $stmt->error . "</p>";
}
$stmt->close();
$conn->close();
}
function display() {
$conn = connect();
$result = $conn->query("SELECT * FROM student");
echo "<table border='1' cellpadding='5'>
<tr><th>ID</th><th>Name</th><th>Email</th><th>Phone</th></tr>";
while ($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row['id'] . "</td><td>" . htmlspecialchars($row['name']) .
"</td><td>" . htmlspecialchars($row['email']) . "</td><td>" .
htmlspecialchars($row['phone']) . "</td></tr>";
}
echo "</table>";
$conn->close();
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
insertdb($_POST["name"], $_POST["email"], $_POST["phone"]);
}
?>
<!DOCTYPE html>
<html>
<body>
<h3>Student Form</h3>
<form method="post" action="">
Name: <input type="text" name="name" required><br><br>
Email: <input type="email" name="email" required><br><br>
Phone: <input type="text" name="phone" required><br><br>
<input type="submit" value="Save">
</form>
<h3>Stored Records</h3>
<?php display(); ?>
</body>
</html>
Working. The form posts to the same page. insertdb() opens a connection and inserts the submitted values using a prepared statement. display() selects all rows from student and prints them in a table, so each new record appears immediately after submission.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 5 marks
Describe client server architecture with its types.
Answer
Client-server architecture. It is a distributed computing model in which tasks are divided between service providers, called servers, and service requesters, called clients. A client sends a request over a network; the server processes it and returns a response. Servers are centralised, always on, and serve many clients (e.g. a browser requesting pages from a web server, or a mail client contacting a mail server).
Advantages: centralised data and security, easy maintenance and updates, scalability, resource sharing. Disadvantages: server failure or overload affects all clients, and network dependence.
Types (tiers).
- 1-tier architecture: presentation, application logic and data are all on one machine (e.g. a standalone desktop application with a local file database). Simple but not shared.
- 2-tier architecture: the client holds the user interface and business logic and talks directly to the database server (e.g. a desktop application using a remote database). Fast and simple, but poor scalability and security since the client accesses the DB directly.
- 3-tier architecture: separates the system into a presentation tier (browser/client), an application tier (web/application server running PHP, Java, etc.) and a data tier (database server). Better security, scalability and maintainability; most web applications use this.
- n-tier (multi-tier) architecture: extends 3-tier by adding more layers such as caching, load balancers, and separate service layers, for large enterprise systems.
Client <--> Application server <--> Database server
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 5 marks
Write a HTML script to create a table with three rows and three columns. The second row third column should contain a text “TU” with link set to www.tu.edu.np . The hieght of second row should be set to 200px.
Answer
<!DOCTYPE html>
<html>
<head>
<title>Table</title>
<style>
table, td { border: 1px solid black; border-collapse: collapse; }
td { padding: 8px; }
</style>
</head>
<body>
<table width="60%">
<tr>
<td>Row1 Col1</td>
<td>Row1 Col2</td>
<td>Row1 Col3</td>
</tr>
<tr style="height:200px;">
<td>Row2 Col1</td>
<td>Row2 Col2</td>
<td><a href="http://www.tu.edu.np">TU</a></td>
</tr>
<tr>
<td>Row3 Col1</td>
<td>Row3 Col2</td>
<td>Row3 Col3</td>
</tr>
</table>
</body>
</html>
The table has three rows and three columns. The <a> tag in the second row, third column links the text "TU" to www.tu.edu.np, and the second row's height is set to 200px using style="height:200px;".
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 5 marks
What is onload event in HTML? Write an HTML script that displays alert message “Hello Nepal” in onload event.
Answer
onload event. The onload event fires when an element or the whole page (for <body> or window) has finished loading completely, including images, scripts and stylesheets. It is commonly used to run initialization code, check browser details, or load cookies.
HTML script.
<!DOCTYPE html>
<html>
<head>
<title>Onload Event</title>
</head>
<body onload="alert('Hello Nepal')">
<h2>Welcome</h2>
</body>
</html>
An equivalent version using a function:
<script>
window.onload = function () {
alert("Hello Nepal");
};
</script>
When the page finishes loading, an alert box with the message "Hello Nepal" is displayed.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 5 marks
How internal and external CSS differ from each other. Illustrate with example.
Answer
Internal CSS is written inside a <style> element in the <head> of the HTML page and applies only to that page.
External CSS is written in a separate .css file and linked to pages using <link rel="stylesheet" href="style.css"> in the head. One file can style many pages.
| Basis | Internal CSS | External CSS |
|---|---|---|
| Location | <style> tag inside the same HTML file | Separate .css file |
| Scope | Single page | Multiple pages / whole website |
| Reusability | Poor | High |
| Maintenance | Must edit each page | Change one file, all pages update |
| Loading | No extra request, but page size grows | Extra HTTP request, but file is cached by browser |
| Separation of content and style | Partial | Complete |
Internal CSS example.
<html>
<head>
<style>
h1 { color: blue; text-align: center; }
p { font-size: 16px; }
</style>
</head>
<body>
<h1>Internal CSS</h1>
<p>Styled in the same file.</p>
</body>
</html>
External CSS example.
style.css:
h1 { color: blue; text-align: center; }
p { font-size: 16px; }
index.html:
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>External CSS</h1>
<p>Styled from style.css.</p>
</body>
</html>
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 5 marks
How can you define array in javascript ? Create an array Fruit with its elements “apple”, “banana”, “mango”, “grape” and print the array.
Answer
Defining arrays in JavaScript. An array is an object that stores multiple values in one variable, accessed by a zero-based index. It can be defined in these ways:
- Array literal (most common):
var a = [1, 2, 3]; - Using the
Arrayconstructor:var a = new Array(1, 2, 3); - Creating an empty array and assigning elements:
var a = []; a[0] = 1;
Fruit array and printing.
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var Fruit = ["apple", "banana", "mango", "grape"];
// print the whole array
document.getElementById("demo").innerHTML = Fruit;
console.log(Fruit);
// print each element
for (var i = 0; i < Fruit.length; i++) {
document.write("<br>" + Fruit[i]);
}
</script>
</body>
</html>
Output: apple,banana,mango,grape followed by each fruit on a separate line.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 5 marks
How can you transform XML document into HTML using XSLT. Support your answer with an example.
Answer
XSLT. XSLT (eXtensible Stylesheet Language Transformations) is a language for transforming an XML document into another format such as HTML, using a stylesheet made of templates. The XSLT processor (usually in the browser) reads the XML, matches nodes using XPath, and applies templates to produce the output.
Steps.
- Create the XML document and link the stylesheet using
<?xml-stylesheet type="text/xsl" href="students.xsl"?>. - Create the XSL file with
<xsl:stylesheet>. - Use
<xsl:template match="/">to output HTML,<xsl:for-each select="...">to loop over nodes and<xsl:value-of select="...">to print values.
students.xml
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="students.xsl"?>
<students>
<student>
<name>Ram</name>
<age>21</age>
</student>
<student>
<name>Sita</name>
<age>20</age>
</student>
</students>
students.xsl
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<h2>Student List</h2>
<table border="1">
<tr><th>Name</th><th>Age</th></tr>
<xsl:for-each select="students/student">
<tr>
<td><xsl:value-of select="name"/></td>
<td><xsl:value-of select="age"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
Opening students.xml in a browser shows an HTML table with the two students; the XML data is unchanged, only presented as HTML.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 5 marks
Write a PHP function add that takes two arguments as an input and return their sum.
Answer
<?php
function add($a, $b) {
return $a + $b;
}
$sum = add(10, 25);
echo "Sum = " . $sum;
?>
Output:
Sum = 35
The function add receives two arguments, computes their sum using +, and returns it to the caller with return. The returned value is stored in $sum and printed.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 5 marks
Define cookie. Write a PHP program to create and retrive a cookie.
Answer
Cookie. A cookie is a small piece of data (up to about 4 KB) that a web server sends to the browser and which the browser stores on the client computer. The browser sends it back with every later request to the same site. Cookies are used to remember users, preferences, login state and for tracking. In PHP, a cookie is created with setcookie() and read through the superglobal $_COOKIE.
Syntax: setcookie(name, value, expire, path, domain, secure, httponly);
setcookie() must be called before any HTML output.
PHP program to create and retrieve a cookie.
<?php
// create cookie (valid for 30 days)
$cookie_name = "user";
$cookie_value = "Ram";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
?>
<!DOCTYPE html>
<html>
<body>
<?php
// retrieve cookie
if (!isset($_COOKIE[$cookie_name])) {
echo "Cookie '" . $cookie_name . "' is set now. Reload the page to read it.";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>
On the first visit the cookie is created; on the next request the browser sends it, so $_COOKIE["user"] returns "Ram". To delete the cookie, set its expiry time in the past: setcookie("user", "", time() - 3600);.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 5 marks
What is text-overflow property in CSS ? How can you use clip and ellipseis in text-overflow ?
Answer
text-overflow property. The CSS text-overflow property specifies how overflowed text that is hidden (cut off because it does not fit in its container) is shown to the user. It works only on block containers where the content overflows, and requires overflow: hidden and normally white-space: nowrap.
Values:
clip(default): the text is simply cut off at the edge of the box; characters may be clipped mid-way.ellipsis: the clipped text is replaced by an ellipsis (...) to show that more text exists.
Example.
<!DOCTYPE html>
<html>
<head>
<style>
div.box {
width: 200px;
white-space: nowrap;
overflow: hidden;
border: 1px solid black;
margin-bottom: 10px;
}
.clip { text-overflow: clip; }
.ellipsis { text-overflow: ellipsis; }
</style>
</head>
<body>
<div class="box clip">This is a very long text that does not fit in the box.</div>
<div class="box ellipsis">This is a very long text that does not fit in the box.</div>
</body>
</html>
The first box shows the text cut off abruptly; the second shows the visible part followed by "...".
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2082 · 10 marks
Define CSS. What is the use of CSS shadow effects? Write an HTML script with proper CSS as per the following description. Display a text content “CSIT Exam” in a div with id div1. The text should have a horizontal shadow of 3px and a vertical shadow of 2px. The shadow color should be green. Also set the horizontal and vertical shadow of the div to 10px respectively with the shadow color of div to blue.
Answer
CSS. CSS (Cascading Style Sheets) is a style sheet language used to control the presentation of HTML documents: colours, fonts, layout, spacing and so on. It separates content (HTML) from design, allows one stylesheet to style many pages, and makes pages easier to maintain.
Use of CSS shadow effects. Shadows add depth and emphasis to a page. text-shadow adds a shadow to text (h-offset v-offset blur color) and box-shadow adds a shadow around an element's box (h-offset v-offset blur spread color). They are used to make headings readable, highlight cards and buttons, and create 3D or raised appearances without images.
HTML script.
<!DOCTYPE html>
<html>
<head>
<title>Shadow Effects</title>
<style>
#div1 {
width: 300px;
height: 100px;
padding: 20px;
font-size: 30px;
text-shadow: 3px 2px green;
box-shadow: 10px 10px blue;
}
</style>
</head>
<body>
<div id="div1">CSIT Exam</div>
</body>
</html>
The text has a horizontal shadow of 3px and vertical shadow of 2px in green (text-shadow: 3px 2px green), and the div has a 10px horizontal and 10px vertical blue shadow (box-shadow: 10px 10px blue).
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2082 · 10 marks
What are jQuery selectors? Explain jQuery callback and chaining effects with appropriate jQuery scripts.
Answer
jQuery selectors. jQuery is a JavaScript library. Selectors are used to find and select HTML elements so that actions can be applied to them. They are written inside $() and are based on CSS syntax, with some extra ones.
| Selector | Example | Selects |
|---|---|---|
| Element | $("p") | all <p> elements |
| Id | $("#demo") | element with id demo |
| Class | $(".test") | all elements of class test |
| All | $("*") | every element |
| Multiple | $("h1, p") | all h1 and p |
| Attribute | $("[href]") | elements having href |
| Pseudo | $("p:first"), $("li:even") | first paragraph, even list items |
| Descendant | $("div p") | p inside div |
$(document).ready(function () {
$("p").css("color", "blue"); // element selector
$("#title").hide(); // id selector
$(".note").css("background", "yellow"); // class selector
});
jQuery callback. JavaScript statements run line by line, but effects such as hide(), fadeOut() and slideUp() take time, so the next line may run before the effect finishes. A callback is a function passed as the last argument of an effect method and executed only after that effect is complete.
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function () {
$("#btn").click(function () {
$("#box").hide(1000, function () {
alert("The box is now hidden"); // runs after hide finishes
});
});
});
</script>
<button id="btn">Hide</button>
<div id="box">Box</div>
jQuery chaining. Chaining runs multiple methods on the same element in one statement, because each method returns the jQuery object. It avoids selecting the element repeatedly and gives shorter, faster code.
<script>
$(document).ready(function () {
$("#btn2").click(function () {
$("#box2").css("color", "red").slideUp(1000).slideDown(1000);
});
});
</script>
<button id="btn2">Chain</button>
<div id="box2">Chaining demo</div>
Here, the colour of #box2 is set to red, then it slides up, then slides down, in order. The effects in the chain are queued, so each starts after the previous one finishes.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2082 · 10 marks
What is the use of XML? Create a XML file having complex type elements containing other elements and text. At least one element should contain an attribute. Similarly, there should be elements containing string, integer and date type values. Now write the equivalent XSD for the XML.
Answer
Use of XML.
- To store and transport data in a platform-independent, text-based format.
- To exchange data between different applications and systems, e.g. web services, SOAP and RSS feeds.
- To separate data from presentation; XSLT or CSS can render the same data in different forms.
- For configuration files and for defining other languages (XHTML, SVG, MathML).
- Because it is self-describing and extensible, users can create their own tags and validate the structure with DTD or XSD.
XML file (complex elements, attribute, string, integer, date).
<?xml version="1.0" encoding="UTF-8"?>
<library>
<book isbn="978-9937-001">
<title>Web Technology</title>
<author>Hari Prasad</author>
<pages>350</pages>
<price>550</price>
<publishedDate>2022-05-15</publishedDate>
<publisher>
<name>Kathmandu Publications</name>
<city>Kathmandu</city>
</publisher>
</book>
</library>
Here library, book and publisher are complex-type elements containing other elements; isbn is an attribute; title, author are strings, pages, price are integers and publishedDate is a date.
Equivalent XSD.
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="library">
<xs:complexType>
<xs:sequence>
<xs:element name="book" maxOccurs="unbounded">
<xs:complexType>
<xs:sequence>
<xs:element name="title" type="xs:string"/>
<xs:element name="author" type="xs:string"/>
<xs:element name="pages" type="xs:integer"/>
<xs:element name="price" type="xs:integer"/>
<xs:element name="publishedDate" type="xs:date"/>
<xs:element name="publisher">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="city" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="isbn" type="xs:string" use="required"/>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2082 · 5 marks
Define web clients and web servers with examples.
Answer
Web client. A web client is software that requests resources from a web server on behalf of a user, using HTTP/HTTPS, and then displays or processes the response. The most common web client is a web browser. The client sends a request (URL, method, headers), receives a response (status code, headers, content) and renders HTML, CSS, JavaScript, images and so on.
Examples: Google Chrome, Mozilla Firefox, Microsoft Edge, Safari; also command-line clients such as curl and wget, mobile apps that call web APIs, and search engine crawlers.
Web server. A web server is software (running on a host computer) that listens for HTTP/HTTPS requests, locates or generates the requested resource, and sends it back to the client. It can serve static files (HTML, images) directly or pass requests to server-side programs (PHP, Node.js, Java servlets) to produce dynamic content. It also handles logging, security, virtual hosts and access control.
Examples: Apache HTTP Server, Nginx, Microsoft IIS, Apache Tomcat, LiteSpeed.
How they work together.
- The user types a URL such as
http://www.example.com/index.htmlin the browser (client). - The browser resolves the domain name through DNS and opens a TCP connection to the server (port 80 for HTTP, 443 for HTTPS).
- The browser sends an HTTP request:
GET /index.html HTTP/1.1. - The web server finds the file (or runs a script) and returns an HTTP response, e.g.
200 OKwith the HTML. - The browser renders the page and requests any extra resources (CSS, images, scripts).
| Aspect | Web client | Web server |
|---|---|---|
| Role | Requests and displays resources | Stores, generates and serves resources |
| Initiates | The communication | Waits and responds |
| Examples | Chrome, Firefox, curl | Apache, Nginx, IIS |
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2082 · 5 marks
Write a HTML script using audio tag. Set the autoplay, preload and loop properties to appropriate values.
Answer
The HTML5 <audio> element plays sound in the browser without plug-ins. Relevant attributes:
controls: shows play, pause and volume controls.autoplay: starts playing as soon as the page is ready (many browsers block autoplay with sound unless the audio ismutedor the user has interacted with the page).preload: hint about loading; valuesauto(load whole file),metadata(load only duration etc.) ornone.loop: restarts the audio when it ends.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Audio Tag Example</title>
</head>
<body>
<h2>Background Music</h2>
<audio controls autoplay loop preload="auto">
<source src="song.mp3" type="audio/mpeg">
<source src="song.ogg" type="audio/ogg">
Your browser does not support the audio element.
</audio>
</body>
</html>
Here autoplay starts the music automatically, loop makes it repeat endlessly, and preload="auto" tells the browser to download the whole file in advance so playback begins quickly. Two <source> elements give alternative formats; the browser plays the first one it supports, and the text inside the tag is the fallback for old browsers.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2082 · 5 marks
Write HTML script to demonstrate the onkeydown and onkeypress events.
Answer
onkeydown fires when a key is pressed down (for every key, including Shift, Ctrl, arrows, Backspace). onkeypress fires when a key that produces a character is pressed (it does not fire for non-character keys such as arrows or Shift, and it is deprecated in modern browsers but still widely taught). onkeyup fires when the key is released.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Keyboard Events</title>
<script>
function keyDownHandler(e) {
document.getElementById("down").innerHTML =
"onkeydown: key = " + e.key + ", keyCode = " + e.keyCode;
}
function keyPressHandler(e) {
document.getElementById("press").innerHTML =
"onkeypress: character = " + String.fromCharCode(e.charCode || e.keyCode);
}
</script>
</head>
<body>
<h3>Type something in the box</h3>
<input type="text" id="txt" onkeydown="keyDownHandler(event)"
onkeypress="keyPressHandler(event)">
<p id="down"></p>
<p id="press"></p>
</body>
</html>
Working: when the user presses a letter such as a, both events fire (keydown first, then keypress) and both messages appear. If the user presses an arrow key or Shift, only the onkeydown message is updated, which shows the difference between the two events.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2082 · 5 marks
Write a HTML script with proper JavaScript that will take an input from prompt box and display the input as output using the alert box.
Answer
The prompt() method shows a dialog with a text field and returns the entered string (or null if Cancel is pressed). The alert() method shows a message dialog.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Prompt and Alert</title>
<script>
function showInput() {
var name = prompt("Please enter your name:", "");
if (name !== null && name !== "") {
alert("You entered: " + name);
} else {
alert("No input was given.");
}
}
</script>
</head>
<body>
<button onclick="showInput()">Click to enter data</button>
</body>
</html>
When the button is clicked, the prompt box asks for a value. After pressing OK, the entered text is stored in the variable name and displayed using the alert box. If the user cancels or leaves the field empty, the program reports that no input was given.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2082 · 5 marks
Create an HTML page containing three paragraphs p1, p2 and p3 with some contents. Write internal CSS to set the position of p1 to relative, p2 to float and p3 to absolute.
Answer
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>CSS Positioning</title>
<style>
p {
width: 250px;
padding: 10px;
border: 1px solid #333;
}
#p1 {
position: relative;
left: 40px;
top: 10px;
background-color: #cfe8ff;
}
#p2 {
float: left;
background-color: #d4f5d4;
}
#p3 {
position: absolute;
top: 300px;
right: 20px;
background-color: #ffe0b3;
}
</style>
</head>
<body>
<p id="p1">Paragraph 1: positioned relative to its normal position, shifted 40px right and 10px down.</p>
<p id="p2">Paragraph 2: floated to the left so that following content wraps around it.</p>
<p id="p3">Paragraph 3: positioned absolutely, relative to the nearest positioned ancestor (here the page), 300px from the top and 20px from the right.</p>
</body>
</html>
Explanation:
position: relativekeepsp1in the normal flow but offsets it from where it would normally be; its original space is preserved.float: leftremovesp2from the normal flow and pushes it to the left edge; text and other inline content wrap around it.position: absoluteremovesp3from the flow completely and places it at the given coordinates relative to the nearest positioned ancestor (or the initial containing block); other elements ignore its space.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2082 · 5 marks
What is the use of alert box? Write a JavaScript program to show the use of RegExp object.
Answer
Use of the alert box. The alert() method of the window object displays a modal dialog with a message and an OK button. It is used to give the user information, warnings or error messages (for example, form validation failures) and to debug scripts quickly. The page is blocked until the user clicks OK. Syntax: alert("message");
RegExp object. RegExp represents a regular expression, a pattern used for matching text. It can be created as /pattern/flags or new RegExp("pattern", "flags"). Common methods are test() (returns true or false) and exec() (returns match details); strings also have match(), search() and replace().
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>RegExp Example</title>
<script>
function checkData() {
var email = document.getElementById("email").value;
var phone = document.getElementById("phone").value;
var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
var phonePattern = new RegExp("^9[78][0-9]{8}$");
if (!emailPattern.test(email)) {
alert("Invalid email address.");
} else if (!phonePattern.test(phone)) {
alert("Invalid phone number. It must be a 10 digit Nepali mobile number.");
} else {
alert("Email and phone number are valid.");
}
var text = "Web Technology is the study of web";
var count = text.match(/web/gi).length;
alert("The word 'web' appears " + count + " times.");
}
</script>
</head>
<body>
Email: <input type="text" id="email"><br><br>
Phone: <input type="text" id="phone"><br><br>
<button onclick="checkData()">Validate</button>
</body>
</html>
The email pattern requires a user name, @, a domain and an extension of at least two letters. The phone pattern accepts 10 digits beginning with 97 or 98. The test() method returns true when the pattern matches, and alert() reports the result. The last part uses the flags g (global) and i (ignore case) to count that "web" appears 2 times in the sample text ("Web" and "web").
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2082 · 5 marks
Write a PHP program to demonstrate the concept of inheritance.
Answer
Inheritance lets a child (derived) class acquire the properties and methods of a parent (base) class using the extends keyword. The child can add new members or override inherited methods, and can call the parent's version with parent::.
<?php
// Base class
class Person {
protected $name;
protected $age;
public function __construct($name, $age) {
$this->name = $name;
$this->age = $age;
}
public function display() {
echo "Name: $this->name<br>";
echo "Age: $this->age<br>";
}
}
// Derived class
class Student extends Person {
private $roll;
private $course;
public function __construct($name, $age, $roll, $course) {
parent::__construct($name, $age); // call parent constructor
$this->roll = $roll;
$this->course = $course;
}
// overriding the parent method
public function display() {
parent::display();
echo "Roll No: $this->roll<br>";
echo "Course: $this->course<br>";
}
}
$s = new Student("Ram Sharma", 20, 15, "BSc CSIT");
$s->display();
?>
Output:
Name: Ram Sharma
Age: 20
Roll No: 15
Course: BSc CSIT
Student inherits name, age and the constructor logic from Person (protected members are accessible in the child), adds its own properties roll and course, and overrides display() while reusing the parent's output through parent::display(). This shows code reuse and polymorphism.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2082 · 5 marks
Write a PHP program to show insertion of multiple data into a database table.
Answer
Multiple rows can be inserted either by running several INSERT statements or by one statement with many value lists. The program below uses MySQLi with a prepared statement inside a loop. Assume a database college with the table:
CREATE TABLE students (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50),
email VARCHAR(80),
age INT
);
<?php
$conn = new mysqli("localhost", "root", "", "college");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// data to insert
$students = [
["Ram Sharma", "ram@example.com", 20],
["Sita Thapa", "sita@example.com", 21],
["Hari Karki", "hari@example.com", 19],
["Gita Rai", "gita@example.com", 22]
];
$stmt = $conn->prepare("INSERT INTO students (name, email, age) VALUES (?, ?, ?)");
$stmt->bind_param("ssi", $name, $email, $age);
$count = 0;
foreach ($students as $row) {
$name = $row[0];
$email = $row[1];
$age = $row[2];
if ($stmt->execute()) {
$count++;
} else {
echo "Error inserting $name: " . $stmt->error . "<br>";
}
}
echo "$count records inserted successfully.";
$stmt->close();
$conn->close();
?>
Alternative single-query form: INSERT INTO students (name, email, age) VALUES ('Ram','ram@example.com',20), ('Sita','sita@example.com',21); and, with MySQLi, $conn->multi_query($sql) can run several statements separated by semicolons. Prepared statements are preferred because they prevent SQL injection and the statement is parsed once and executed many times. Output: 4 records inserted successfully.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2082 · 5 marks
Create a PHP form with form elements. Write a program to perform form validation. Use your own assumptions for the validation.
Answer
Assumptions: name is required and contains only letters and spaces; email must be valid; phone must be a 10-digit number starting with 97 or 98; age must be a number between 16 and 60; password must be at least 8 characters; gender must be selected.
<?php
$errors = [];
$name = $email = $phone = $age = $gender = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = trim($_POST["name"] ?? "");
$email = trim($_POST["email"] ?? "");
$phone = trim($_POST["phone"] ?? "");
$age = trim($_POST["age"] ?? "");
$gender = $_POST["gender"] ?? "";
$pass = $_POST["password"] ?? "";
if ($name == "") {
$errors[] = "Name is required.";
} elseif (!preg_match("/^[A-Za-z ]+$/", $name)) {
$errors[] = "Name can contain only letters and spaces.";
}
if ($email == "") {
$errors[] = "Email is required.";
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = "Invalid email format.";
}
if (!preg_match("/^9[78][0-9]{8}$/", $phone)) {
$errors[] = "Phone must be 10 digits starting with 97 or 98.";
}
if (!is_numeric($age) || $age < 16 || $age > 60) {
$errors[] = "Age must be a number between 16 and 60.";
}
if ($gender == "") {
$errors[] = "Please select a gender.";
}
if (strlen($pass) < 8) {
$errors[] = "Password must be at least 8 characters.";
}
if (empty($errors)) {
echo "<p style='color:green'>Form submitted successfully. Welcome, "
. htmlspecialchars($name) . "!</p>";
} else {
foreach ($errors as $e) {
echo "<p style='color:red'>" . htmlspecialchars($e) . "</p>";
}
}
}
?>
<!DOCTYPE html>
<html>
<head><meta charset="UTF-8"><title>Registration Form</title></head>
<body>
<h2>Registration Form</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>">
Name: <input type="text" name="name" value="<?php echo htmlspecialchars($name); ?>"><br><br>
Email: <input type="text" name="email" value="<?php echo htmlspecialchars($email); ?>"><br><br>
Phone: <input type="text" name="phone" value="<?php echo htmlspecialchars($phone); ?>"><br><br>
Age: <input type="text" name="age" value="<?php echo htmlspecialchars($age); ?>"><br><br>
Gender:
<input type="radio" name="gender" value="Male"> Male
<input type="radio" name="gender" value="Female"> Female
<input type="radio" name="gender" value="Other"> Other<br><br>
Password: <input type="password" name="password"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
The form posts to the same page. On submission the script trims the inputs, checks each field with preg_match, filter_var and is_numeric, collects the messages in the $errors array, and shows them. If there are no errors, a success message is printed. htmlspecialchars() escapes output to prevent XSS, and the entered values are redisplayed so the user need not retype them.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
Questions from TU BSc CSIT 2076 Cryptography (TU IOST board exam, 2076), TU BSc CSIT 2078 Cryptography (TU IOST board exam, 2078), TU BSc CSIT 2079 Cryptography (TU IOST board exam, 2079), TU BSc CSIT 2080 Cryptography (TU IOST board exam, 2080), TU BSc CSIT 2081 Cryptography (TU IOST board exam, 2081), TU BSc CSIT 2082 Cryptography (TU IOST board exam, 2082), TU BSc CSIT 2076 Design and Analysis of Algorithms (TU IOST board exam, 2076), TU BSc CSIT 2078 Design and Analysis of Algorithms (TU IOST board exam, 2078), TU BSc CSIT 2079 Design and Analysis of Algorithms (TU IOST board exam, 2079), TU BSc CSIT 2080 Design and Analysis of Algorithms (TU IOST board exam, 2080), TU BSc CSIT 2081 Design and Analysis of Algorithms (TU IOST board exam, 2081), TU BSc CSIT 2082 Design and Analysis of Algorithms (TU IOST board exam, 2082), TU BSc CSIT 2080 Image Processing (TU IOST board exam, 2080), TU BSc CSIT 2081 Image Processing (TU IOST board exam, 2081), TU BSc CSIT 2082 Image Processing (TU IOST board exam, 2082), TU BSc CSIT 2080 Multimedia Computing (TU IOST board exam, 2080), TU BSc CSIT 2081 Multimedia Computing (TU IOST board exam, 2081), TU BSc CSIT 2082 Multimedia Computing (TU IOST board exam, 2082), TU BSc CSIT 2076 System Analysis and Design (TU IOST board exam, 2076), TU BSc CSIT 2078 System Analysis and Design (TU IOST board exam, 2078), TU BSc CSIT 2079 System Analysis and Design (TU IOST board exam, 2079), TU BSc CSIT 2080 System Analysis and Design (TU IOST board exam, 2080), TU BSc CSIT 2081 System Analysis and Design (TU IOST board exam, 2081), TU BSc CSIT 2082 System Analysis and Design (TU IOST board exam, 2082), TU BSc CSIT 2076 Society and Ethics in Information Technology (TU IOST board exam, 2076), TU BSc CSIT 2078 Society and Ethics in Information Technology (TU IOST board exam, 2078), TU BSc CSIT 2079 Society and Ethics in Information Technology (TU IOST board exam, 2079), TU BSc CSIT 2076 Simulation and Modeling (TU IOST board exam, 2076), TU BSc CSIT 2078 Simulation and Modeling (TU IOST board exam, 2078), TU BSc CSIT 2079 Simulation and Modeling (TU IOST board exam, 2079), TU BSc CSIT 2080 Simulation and Modeling (TU IOST board exam, 2080), TU BSc CSIT 2081 Simulation and Modeling (TU IOST board exam, 2081), TU BSc CSIT 2082 Simulation and Modeling (TU IOST board exam, 2082), TU BSc CSIT 2076 Web Technology (TU IOST board exam, 2076), TU BSc CSIT 2078 Web Technology (TU IOST board exam, 2078), TU BSc CSIT 2079 Web Technology (TU IOST board exam, 2079), TU BSc CSIT 2080 Web Technology (TU IOST board exam, 2080), TU BSc CSIT 2081 Web Technology (TU IOST board exam, 2081) and TU BSc CSIT 2082 Web Technology (TU IOST board exam, 2082). Answers are written for this site; check them against your class notes.