[go: up one dir, main page]

0% found this document useful (0 votes)
19 views23 pages

Webprogramming2

The document contains various JavaScript code examples demonstrating different functionalities such as creating arrays, calculating averages, handling events, and manipulating strings. Each example includes HTML and JavaScript code snippets along with descriptions of their purpose. The examples cover a wide range of topics, including user input handling, error handling, and displaying information dynamically on web pages.

Uploaded by

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

Webprogramming2

The document contains various JavaScript code examples demonstrating different functionalities such as creating arrays, calculating averages, handling events, and manipulating strings. Each example includes HTML and JavaScript code snippets along with descriptions of their purpose. The examples cover a wide range of topics, including user input handling, error handling, and displaying information dynamically on web pages.

Uploaded by

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

2313721033024

Maahi Tated

1.Write a java script to create an array called “skill_course” which stores the skill
courses you learnt in UG, and display the same. Input to the array element should be
from textbox. (Use for... in loop to display the array elements)

Source Code:

<!DOCTYPE html>
<html>
<head>
<title>Skill Courses</title>
</head>
<body>
<input type="text" id="skillCourseInput">
<button onclick="addSkillCourse()">Add Course</button>
<p id="skillCourses"></p>
<script>
var skill_courses = [];
function addSkillCourse() {
var course = document.getElementById("skillCourseInput").value;
skill_courses.push(course);
document.getElementById("skillCourseInput").value = "";
var display = "Skill Courses Learned in UG:<br>";
for (var index in skill_courses) {
display += "- " + skill_courses[index] + "<br>";
}
document.getElementById("skillCourses").innerHTML = display;
}
</script>
</body>
</html>

Output:
2313721033024
Maahi Tated

2. Write a Java Script to find the average mark of a student and display the same in the
textbox. The Mark should be from user input.

Source Code:

<!DOCTYPE html>
<html>
<head>
<title>Average Mark</title>
</head>
<body>
<input type="number" id="mark1" placeholder="Enter Mark 1">
<input type="number" id="mark2" placeholder="Enter Mark 2">
<input type="number" id="mark3" placeholder="Enter Mark 3">
<button onclick="calculateAverage()">Calculate Average</button>
<input type="text" id="average" readonly>
<script>
function calculateAverage() {
let mark1 = parseFloat(document.getElementById("mark1").value);
let mark2 = parseFloat(document.getElementById("mark2").value);
let mark3 = parseFloat(document.getElementById("mark3").value);
if (!isNaN(mark1) && !isNaN(mark2) && !isNaN(mark3)) {
let average = (mark1 + mark2 + mark3) / 3;
document.getElementById("average").value = average.toFixed(2);
} else {
alert("Please enter valid numbers for all marks.");
}
}
</script>
</body>
</html>

Output:

3. Write a JavaScript to accept the subjects you learnt in UG, and display the same
using “with statement”

Source Code:
<!DOCTYPE html>
2313721033024
Maahi Tated

<html>
<head>
<title>Subjects Learned in UG</title>
</head>
<body>
<script>
let subjects = {
subject1: "Operating Systems",
subject2: "Data Mining",
subject3: "Web Programming"
};
with (subjects) {
document.write("Subjects Learned in UG:<br>");
document.write("- " + subject1 + "<br>");
document.write("- " + subject2 + "<br>");
document.write("- " + subject3 + "<br>");
}
</script>
</body>
</html>

Output:

4. Write a JavaScript function to demonstrate the function with variable number of


parameters.

Source Code:

<html>
<head>
<script language = "javascript">
function sum()
{
n=sum.arguments.length
total=0;
for(i=0;i<n;i++){
total += sum.arguments[i]
2313721033024
Maahi Tated

}
return total
}
</script>
</head>
<body>
<script language ="javascript">
x=sum(5,16,70,8,10)
document.write("The sum is:"+ x)
</script>
</body>
</html>

Output:

5. Write a JavaScript to display “Hi Javascript” when you load a page and display
“Bye Javascript” when you unload a page.

Source Code:

<html>
<head>
<title>Page Load and Unload Example</title>
<script>
function sayHello() {
alert('Hai Javascript'); }
function sayGoodbye() {
alert('Bye Javascript');
}
</script>
</head>
<body onload="sayHello()" onunload="sayGoodbye()">
<h2>Page Load and Unload</h2>
<p>This page will alert "Hai Javascript" when it loads and "Bye Javascript" when it
unloads.</p>
</body>
</html>
Output:
2313721033024
Maahi Tated

6. Write a JavaScript to demonstrate the event handling associated with image. (Use
onLoad, onAbort and onError event handling)

Source Code:

<html>
<head>
<title>Image Event Handling</title>
</head>
<body>
<h2>Image Event Handling Example</h2>
<img src="wallpaper2.jpg" onload="loadImage()" width="90" height="100">
<script type="text/javascript">
function loadImage() {
alert("Image is loaded");
}
</script>
<img src="wallpaper2.jpg" onabort="abortImage()" width="90" height="100">
<script type="text/javascript">
function abortImage(){
alert("Error: Loading of the image was aborted");
}
</script>
<img src="wallpaper3.jpg" onerror="errorImage()" width="90" height="100">
<p>A function is triggered if an error occurs when loading the image.</p>
<script type="text/javascript">
function errorImage() {
2313721033024
Maahi Tated

alert('The image could not be loaded.');


}
</script>
</body>
</html>

Output:

7. Write a JavaScript to demonstrate the event handling associated with text box (Use
onChange, onSelect, onFocus and onBlur)

Source Code:

<html>
<head>
<script>
function handleChange(input) {
alert("The text has been changed to: " + input);
}
function handleBlur() {
alert("Seems like your leaving ");
}
function handleFocus() {
alert("now please type your text");
}
2313721033024
Maahi Tated

function handleSelect() {
alert("You selected texts");
}
</script>
</head>
<body>
<h3>Text Box Event Handling Example</h3>
<form>
<input type="text" value="changes here"
onChange="handleChange(this.value)"><br>
<input type="text" value="select here" onSelect="handleSelect()"><br>
<input type="text" placeholder="Focus here" onFocus="handleFocus()"
onBlur="handleBlur()">
</form>
</body>
</html>

Output:
2313721033024
Maahi Tated

8. Write a JavaScript Code to open a page on onMouseOver itself.

Source Code:

<html>
<head><title>Example of onMouseOver Event Handler</title>
<script>
function display()
{
window.location = "reg.html";
}
</script>
</head>
<body>
<h3>Example of onMouseOver Event Handler</h3>
Put your mouse over
<a href=" "
onMouseOver= "display()">
here
</a>
and look at the status bar
(usually at the bottom of your browser window).
</body>
</html>

Output:
2313721033024
Maahi Tated

9. Write a JavaScript to simulate the calculator.

Source Code:

<html>
<head>
<title>Simple Calculator</title>
</head>
<body>
<h1>Simple Calculator</h1>
<input type="number" id="num1" placeholder="Enter first number">
<input type="number" id="num2" placeholder="Enter second number">
<br><br>
<button onclick="add()">+</button>
<button onclick="subtract()">-</button>
<button onclick="multiply()">*</button>
<button onclick="divide()">/</button>
<p id="result"></p>
<script>
function add() {
let num1 = Number(document.getElementById("num1").value);
let num2 = Number(document.getElementById("num2").value);
2313721033024
Maahi Tated

document.getElementById("result").innerHTML = "Result: " + (num1 + num2);


}
function subtract() {
let num1 = Number(document.getElementById("num1").value);
let num2 = Number(document.getElementById("num2").value);
document.getElementById("result").innerHTML = "Result: " + (num1 - num2);
}
function multiply() {
let num1 = Number(document.getElementById("num1").value);
let num2 = Number(document.getElementById("num2").value);
document.getElementById("result").innerHTML = "Result: " + (num1 * num2);
}
function divide() {
let num1 = Number(document.getElementById("num1").value);
let num2 = Number(document.getElementById("num2").value);
if (num2 === 0) {
document.getElementById("result").innerHTML = "Error: Division by zero";
} else {
document.getElementById("result").innerHTML = "Result: " + (num1 / num2);
}
}
</script>
</body>
</html>

Output:

10. Write a JavaScript code to accept a string and perform various string manipulation
functions.

Source Code:
2313721033024
Maahi Tated

<html>
<head>
<title> String Manupulation </title>
<script language ="javascript">
function Manip()
{
str = frm1.t1.value
document.write("The string is :" + str + "<br>")
s = new String(str)
document.write("s.charAt(1) =" + " " + s.charAt(1)+"<br>")
document.write("s.charCodeAt(1) =" + " " + s.charCodeAt(1)+"<br>")
document.write("s.indexOf(is) =" + " " + s.indexOf("is")+"<br>")
document.write("s.lastIndexOf(IS) =" + " " + s.lastIndexOf("IS")+"<br>")
document.write("s.substring(4,13) =" + " " + s.substring(4,13)+"<br>")
document.write("s.toLowerCase() =" + " " + s.toLowerCase()+"<br>")
split = s.split(" ")
for (i=0; i<split.length; ++i)
document.write("split['+i+'] = " +" " + split[i])
}
</script>
</head>
<body>
<form name="frm1">
Enter the String
<input type="text" name="t1" > <br> <br>
<input type="button" name="b1" value="Click" onClick="Manip()">
</body>
</form>
</html>

Output:

11. Write a JavaScript code to find the vowels and consonants in a string.

Source Code:
2313721033024
Maahi Tated

<!DOCTYPE html>
<html>
<head>
<title>Vowels and Consonants</title>
</head>
<body>
<input type="text" id="inputString" placeholder="Enter a string">
<button onclick="findVowelsConsonants()">Find</button>
<p id="result"></p>
<script>
function findVowelsConsonants() {
let str = document.getElementById("inputString").value;
let vowels = "aeiouAEIOU";
let vowelsCount = 0;
let consonantsCount = 0;
for (let i = 0; i < str.length; i++) {
if (vowels.includes(str[i])) {
vowelsCount++;
} else if (/[a-zA-Z]/.test(str[i])) {
consonantsCount++;
}
}
document.getElementById("result").innerHTML =
"Vowels: " + vowelsCount + "<br>" +
"Consonants: " + consonantsCount;
}
</script>
</body>
</html>

Output:

12.Create a user defined object called students display the student name, age, course
and the department the student belongs to.

Source Code:
2313721033024
Maahi Tated

<!DOCTYPE html>
<html>
<head>
<title>Student Information</title>
</head>
<body>
<script>
function Student(name, age, course, department) {
this.name = name;
this.age = age;
this.course = course;
this.department = department;
this.displayInfo = function()
{
document.write("<h2>Student Information</h2>");
document.write("<p>Name: " + this.name + "</p>");
document.write("<p>Age: " + this.age + "</p>");
document.write("<p>Course: " + this.course + "</p>");
document.write("<p>Department: " + this.department + "</p>");
document.write("<hr>");
};
}
const student1 = new Student("Alice", 20, "Computer Science", "CSE");
const student2 = new Student("Bob", 21, "Mechanical Engineering", "ME");
student1.displayInfo();
student2.displayInfo();
</script>
</body>
</html>

Output:
2313721033024
Maahi Tated

13. Write a Javascript to handle errors using Error object.


Source Code:
<html>
<head>
<title> Handling errors with the error object </title>
<script language="javascript">
<!--
function getError()
{
try
{
CreateError()
}
catch(errorObject)
{
errorMessage = "Error - Undefined function \n \n"
errorMessage += "Error Number :" +(errorObject.number & 0xFFFF)
errorMessage += errorObject.description
alert(errorMessage)
}
}
-->
</script>
</head>
<body>
<h1> Handling errors with error object </h1>
<form>
<input type="button" onclick="getError()" value="click here">
</form>
</body>
</html>

Output:
2313721033024
Maahi Tated

14. Write a Javascript to handle errors using onError event handling.

Source Code:

<html>
<body>
<p>Use the HTML DOM to assign an "onerror" event to an img element.</p>
<img id="myImg" src="image.gif">
<p id="demo"></p>
<script>
document.getElementById("myImg").onerror = function() {myFunction()};
function myFunction() {
document.getElementById("demo").innerHTML = "The image could not be
loaded.";
}
</script>
</body>
</html>

Output:

15. Write a JavaScript code to display date and time.

Source Code:
2313721033024
Maahi Tated

<!DOCTYPE html>
<html>
<head>
<title>Date and Time</title>
</head>
<body>
<p id="datetime"></p>
<script>
function displayDateTime() {
const now = new Date();
const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric', hour:
'2-digit', minute: '2-digit', second: '2-digit' };
const formattedDateTime = now.toLocaleDateString('en-US', options);
document.getElementById("datetime").innerHTML = formattedDateTime;
}
displayDateTime();
setInterval(displayDateTime, 1000);
</script>
</body>
</html>

Output:

16. Write a Javascript code to open a new window and the window should be closed
on clicking a button

Source Code:

<html>
<head>
<script type="text/javascript">
function open_win()
{
win1 = window.open("reg.html", "win1", "width=250", "height=250")
}
function close_win()
{
if (win1) {
win1.close();
2313721033024
Maahi Tated

}
}
</script>
</head>
<body>
<input type=button value="Open Window" onclick="open_win()" />
<input type=button value="Close Window" onclick="close_win()" />
</body>
</html>

Output:

17. Write a JavaScript code to open a new window, and display “Welcome to my
Page” in the new window.

Source Code:

<html>
<head>
<script type="text/javascript">
function open_win()
2313721033024
Maahi Tated

{
win1 = window.open("reg.html", "win1", "width=250", "height=250")
}
</script>
</head>
<body>
<input type=button value="Open Window" onclick="open_win()" />
</body>
</html>

Output:

18. Write a javaScript code to display “Have a Nice Day” after every 5 seconds

Source Code:

<html>
<head>
<script type="text/javascript">
function timedMsg()
{
var t=setTimeout("alert('Have a Nice Day!')",5000)
2313721033024
Maahi Tated

}
</script>
</head>
<body>
<form>
<input type="button" value="Message Box!"
onClick="timedMsg()">
</form>
<p>Click on the button above. A message will be
displayed after 5 seconds.</p>
</body>
</html>

Output:

19. Write a JavaScript code to open a new window without titlebar,scrollbar,menubar


etc and the window should unload after 30 seconds.

Source Code:

<html>
<head>
<title>Open New Window with Timeout</title>
</head>
<body>
<button onclick="openWindow()">Open New Window</button>
2313721033024
Maahi Tated

<script>
function openWindow() {
var newWindow = window.open("reg.html", "NewWindow",
"width=400,height=300,toolbar=yes,location=yes,menubar=yes,scrollbars=yes,resi
zable=yes");
if (newWindow) {
setTimeout(function() {
newWindow.close();
}, 30000);
} else {
alert("Error: Could not open new window. Pop-ups might be blocked.");
}
}
</script>
</body>
</html>

<html>
<head>
<title>New Window </title>
</head>
<body>
<h1>This is the New Window</h1>
<p>This window will automatically close in 30 seconds or you can close it manually
using the button below.</p>
<script>
function closeWin() {
window.close();
}
</script>
<input type="button" value="Close Window" onclick="closeWin()" />
</body>
</html>

Output:
2313721033024
Maahi Tated

20. Write a JavaScript code to show the usage of Confirm and Prompt methods.

Source Code:

<html>
<head>
<script type="text/javascript">
function disp_confirm()
{
var r=confirm("Press a button")
if (r==true)
{
document.write("You pressed OK!")
}
else
{
document.write("You pressed Cancel!")
}
}
</script>
</head>
<body>
<input type="button" onclick="disp_confirm()"
value="Display a confirm box" />
</body>
2313721033024
Maahi Tated

</html>

<html>
<head>
<script type="text/javascript">
function disp_prompt()
{
var name=prompt("Please enter your name","")
if (name!=null && name!="")
{
document.write("Hello " + name + "!")
}
}
</script>
</head>
<body>
<input type="button" onclick="disp_prompt()"
value="Display a prompt box" />
</body>
</html>

Output:
2313721033024
Maahi Tated

You might also like