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

Master Key CSS (22519)

The documents discuss JavaScript programs and functions related to arrays, strings, dates, and DOM manipulation. They include examples of sorting an array, replacing string values, checking character indexes, and modifying the status bar. Functions for merging arrays, checking first character case, and string conversion between numbers and strings are also explained.

Uploaded by

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

Master Key CSS (22519)

The documents discuss JavaScript programs and functions related to arrays, strings, dates, and DOM manipulation. They include examples of sorting an array, replacing string values, checking character indexes, and modifying the status bar. Functions for merging arrays, checking first character case, and string conversion between numbers and strings are also explained.

Uploaded by

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

Q] JavaScript program that will display Q] Write a Java Script code to display 5

current date in DD/MM/YYYY format. elements of array in sorted order.

<html lang="en"> <html>


<head> <head>
<meta charset="UTF-8"> <title> Array</title>
<meta http-equiv="X-UA-Compatible" </head>
content="IE=edge"> <body>
<meta name="viewport" <script>
content="width=device-width, initial- var arr1 = [ “Red”, “red”, “Blue”,
scale=1.0"> “Green”]
<title>Document</title> document.write(“Before sorting arra1=” +
</head> arr1);
<body> document.write(“<br>After sorting
<script> arra1=” + arr1.sort());
var d=new Date(); </script>
var </body>
currentDate=d.getDate()+'/'+(d.getMonth() </html>
+1)+'/'+d.getFullYear()
document.write(currentDate) Q] Write the use of chatAt() and
</script> indexof() with syntax and example.
</body> charAt()
</html> The charAt() method requires one
argument i.e is the index of the character
Q] Write javascript that will replace that you want to copy.
following specified value with another Syntax:
value in string var SingleCharacter =
String = “I will fail” NameOfStringObject.charAt(index);
Replace “fail” by “pass” Example:
var FirstName = 'Bob';
<html> var Character = FirstName.charAt(0);
<head> indexOf()
<body> The indexOf() method returns the index of
<script> the character passed to it as an
var myStr = ‘I will fail’; argument.
var newStr = myStr.replace(fail, "pass"); If the character is not in the string, this
document.write(newStr); method returns –1.
</script> Syntax:
</body> var indexValue =
</head></html> string.indexOf('character');
Example:
var FirstName = 'Bob';
var IndexValue = FirstName.indexOf('o');
Q] Write a JavaScript program that will Q] Write Java script program which
display list of students in ascending order computes, the average marks of the
according to the marks & calculate the following students then, this average is
average performance of the class. used to determine the corresponding
<html> grade.
<body> <html>
<script> <head>
var students = [["Amit", <title>Compute the average marks and
70],["Sumit",78],["Abhishek", 71],]; grade</title>
var Avgmarks = 0; </head>
for (var i = 0; i < students.length; i++) { <body>
Avgmarks += students[i][1]; <script>
for (var j = i + 1; j < students.length; j++) var students = [['Summit', 80], ['Kalpesh',
{ 77], ['Amit', 88], ['Tejas', 93],
if (students[i] > students[j]) { ['Abhishek', 65]];
a = students[i]; var Avgmarks = 0;
students[i] = students[j]; for (var i=0; i < students.length; i++) {
students[j] = a Avgmarks += students[i][1];
} }
} var avg = (Avgmarks/students.length);
} document.write("Average grade: " +
var avg = Avgmarks / students.length; (Avgmarks)/students.length);
document.write("Average grade: " + document.write("<br>");
Avgmarks / students.length); if (avg < 60){
document.write("<br><br>"); document.write("Grade : E");
for (i = 0; i < students.length; ++i){ }
document.write(students[i]+"<br>") else if (avg < 70) {
} document.write("Grade : D");
</script> }
</body> else if (avg < 80) {
</html> document.write("Grade : C");
} else if (avg < 90) {
document.write("Grade : B");
} else if (avg < 100) {
document.write("Grade : A");
}
</script>
</body>
</html>
Output:
Average grade: 80.6
Grade : B
Q] Write a JavaScript function to merge Q] Write JavaScript function to check
two array & removes all duplicate the first character of a string is
values. uppercase or not.
<html> <html>
<body> <body>
<script> <script>
function mergearr(arr1, arr2) function upper_case(str)
{ {
var arr = arr1.concat(arr2); regexp = /^[A-Z]/;
var uniqueArr = [];for(var i of arr) { if (regexp.test(str))
if(uniqueArr.indexOf(i) === -1) {
{ document.write("String's first character is
uniqueArr.push(i); uppercase");
} }
} else
document.write(uniqueArr); {
} document.write("String's first character is
var array1 = [1, 2, 3,6,8]; not uppercase");
var array2 = [2, 3, 5,56,78,3] }
mergearr(array1, array2); }
</script> upper_case('Abcd');
</body> </script>
</html> </body>
Output: 1,2,3,6,8,5,56,78 </html>
Q] Explain a string functions for
converting string to number and number Q] Write a Java script to modify the
to string. To covert string to number we status bar using on MouseOver and on
can use parseInt() which converts a MouseOut with links. When the user
string number to a integer number. moves his mouse over the links, it will
Similarly we can use parseFloat(), display “MSBTE” in the status bar.
number() for converting string to When the user moves his mouse away
number. from the link the status bar will display
Eg – var a=prompt('Enter a number'); nothing.
var b=parseInt(prompt('Enter a number'));
document.write(typeof a+"<br>"); <html>
document.write(typeof b); <head>
To convert form number to string we can <title>JavaScript Status
use toString() Bar</title></head>
<html> <body>
<body> <a href=" https://msbte.org.in/"
<p>toString() returns a number as a onMouseOver="window.status='MSBTE';
string:</p> return true"
<script> onMouseOut="window.status='';return
let num = 12; true">
let text = num.toString(); MSBTE
document.write(num) </a>
</script> </body>
</body> </html>
</html>
Q] Describe text Rollover with the help of example.
Rollover means a webpage changes when the user moves his or her mouse over an object on
the page. It is often used in advertising. There are two ways to create rollover, using plain
HTML or using a mixture of JavaScript and HTML. We will demonstrate the creation of
rollovers using both methods.
The keyword that is used to create rollover is the <onmousover> event. For example, we want
to create a rollover text that appears in a text area. The text “What is rollover?” appears when
the user place his or her mouse over the text area and the rollover text changes to “Rollover
means a webpage changes when the user moves his or her mouse over an object on the page”
when the user moves his or her mouse away from the text area.
The HTML script is shown in the following example:
Example:
<html>
<head></head>
<Body>
<textarea rows="2" cols="50" name="rollovertext" onmouseover="this.value='What
is rollover?'"
onmouseout="this.value='Rollover means a webpage changes when the user moves
his or her mouse over an object on the page'"></textarea>
</body>
</html>

Q] Describe Quantifiers with the help of example.


The frequency or position of bracketed character sequences and single characters can be
denoted by a special character. Each special character has a specific connotation. The +, *, ?,
and $ flags all follow a character sequence.

Quantifer Meaning
p+ Matches its preceding pattern for one or more number of times.
p* Matches its preceding pattern for zero or more number of times.
p? Matches its preceding pattern for zero or one number of times.
p{n} Matches its preceding pattern exactly for n number of times.
p{m,n} Matches its preceding pattern for m to n number of times.

Example:
<html>
<body>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction()
{
var str = "100, 1000 or 10000?";
var patt1 = /\d{3,4}/g;
var result = str.match(patt1);
document.getElementById("demo").innerHTML = result;
}
</script>
</body>
</html>
Q] Describe frameworks of JavaScript & its application.
Frameworks of JavaScript:
1. ReactJs:
React is based on a reusable component. Simply put, these are code blocks that can be classified
as either classes or functions. Each component represents a specific part of a page, such as a
logo, a button, or an input box. The parameters they use are called props, which stands for
properties.
Applications:
React is a JavaScript library developed by Facebook which, among other things, was used to
build Instagram.com.
2. Angular:
Google operates this framework and is designed to use it to develop a Single Page Application
(SPA). This development framework is known primarily because it gives developers the best
conditions to combine JavaScript with HTML and CSS. Google operates this framework and
is designed to use it to develop a Single Page Application (SPA). This development framework
is known primarily because it gives developers the best conditions to combine JavaScript with
HTML and CSS.
Applications:
Microsoft Office ,Gmail, Forbes, PayPal, Grasshopper, Samsung, Delta
3. Vue.js:
Vue is an open-source JavaScript framework for creating a creative UI. The integration with
Vue in projects using other JavaScript libraries is simplified because it is designed to be
adaptable.
Application:
VueJS is primarily used to build web interfaces and one-page applications. It can also be
applied to both desktop and mobile app development.
4. jQuery:
It is a cross-platform JavaScript library designed to simplify HTML client-side scripting. You
can use the jQuery API to handle, animate, and manipulate an event in an HTML document,
also known as DOM. Also, jQuery is used with Angular and React App building tools.
Applications:
1. JQuery can be used to develop Ajax based applications.
2. It can be used to make code simple, concise and reusable.
3. It simplifies the process of traversal of HTML DOM tree.
4. It can also handle events, perform animation and add ajax support in web applications.
5. Node.js:
Node.js is an open-source, server-side platform built on the Google Chrome JavaScript Engine.
Node.js is an asynchronous, single-threaded, non-blocking I/O model that makes it lightweight
and efficient.
Applications:
Paypal, LinkedIn, Yahoo, Mozilla, Netflix, Uber, Groupon, GoDaddy, eBay
Q] Describe how to link banner advertisement to URL with example.
Ans:
The banner advertisement is the hallmark of every commercial web page. It is typically
positioned near the top of the web page, and its purpose is to get the visitor's attention by doing
all sorts of clever things. To get additional information, the visitor is expected to click the
banner so that a new web page opens. You can link a banner advertisement to a web page by
inserting a hyperlink into your web page that calls a JavaScript function rather than the URL
of a web page. The JavaScript then determines the URL that is associated with the current
banner and loads the web page that is associated with the URL.
Example:
<html> if (CurrentBanner == NumOfBanners) {
<head> CurrentBanner = 0
<title>Link Banner Ads</title> }
<script language="Javascript" document.RotateBanner.src=
type="text/javascript"> Banners[CurrentBanner]
Banners = new Array('1.jpg','2.jpg','3.jpg') setTimeout("DisplayBanners()",1000)
BannerLink = new Array( }
'google.com/','vpt.edu.in/', 'msbte.org.in/'); }
CurrentBanner = 0; </script>
NumOfBanners = Banners.length; </head>
function LinkBanner() <body onload="DisplayBanners()" >
{ <center>
document.location.href = <a href="javascript: LinkBanner()"><img
"http://www." + src="1.jpg"
BannerLink[CurrentBanner]; width="400" height="75"
} name="RotateBanner" /></a>
function DisplayBanners() { </center>
if (document.images) { </body>
CurrentBanner++ </html>

Q] Develop a JavaScript program to create Rotating Banner Ads.


Ans:
<html > document.RotateBanner.src=
<head> Banners[CurrentBanner];
<title>Banner Ads</title> setTimeout("DisplayBanners()",1000);
<script> }
Banners = new Array('1.jpg','2.jpg','3.jpg'); }
CurrentBanner = 0; </script>
function DisplayBanners() </head>
{ <body onload="DisplayBanners()" >
if (document.images); <center>
{ <img src="1.jpg" width="400"
CurrentBanner++; height="75" name="RotateBanner" />
if (CurrentBanner == Banners.length) </center>
{ </body>
CurrentBanner = 0; </html>
}
Q] Write the JavaScript code for below <tr>
operations: <td>Pin code : </td>
<td> <input type="number" id="pin"
required></td>
</tr>
<tr>
<td></td>
<td><button
onclick="submit()">Submit</button></td>
</tr>
(1) Name, Email & Pin Code should not </tbody>
be blank. </table>
(2) Pin Code must contain 6 digits & it </body>
should not be accept any characters. <script>
function submit()
<html> {
<head> var name =
<style> document.getElementById("name").value;
table,tr,td var email =
{ document.getElementById("email").value;
border: solid black 1px; var pin =
border-collapse: collapse; Number(document.getElementById("pin")
} .value);
if(name.length==0 || email.length==0 ||
td pin.length==0)
{ {
padding: 10px; alert("Please enter value in all fields.")
} }
</style> else
</head> {
<body> var pinpattern =/^[4]{1}[0-9]{5}$/;
<table> if( pinpattern.test(pin))
<tbody> {
<tr> alert("Perfect Pin code");
<td>Name : </td> }
<td> <input type="text" id="name" else
required></td> {
</tr> alert("Wrong Pin code.");
<tr> }
<td>Email : </td> }
<td> <input type="email" id="email" }
required></td> </script>
</tr> </html>
Q] Write a java script that displays return false;
textboxes for accepting name & email }
ID & a submit button. Write java script var emailID =
code such that when the user clicks on document.myForm.EMail.value;
submit button atpos = emailID.indexOf("@");
(1) Name Validation dotpos = emailID.lastIndexOf(".");
(2) Email ID Validation. if (atpos < 1 || ( dotpos - atpos < 2 )) {
alert("Please enter correct email ID")
<html> document.myForm.EMail.focus() ;
<head> return false;
<title>Form Validation</title> }
</head> return( true );
<body> }
<form action = "/cgi-bin/test.cgi" name = //-->
"myForm" onsubmit = </script>
"return(validate());">
<table cellspacing = "2" cellpadding = "2" Q] Write a webpage that displays a form
border = "1"> that contains an input for user name and
<tr> password. User is prompted to enter the
<td align = "right">Name</td> input user name and password and
<td><input type = "text" name = "Name" password becomes the value of the
/></td> cookie. Write the JavaScript function for
</tr> storing the cookies. It gets executed when
<tr> the password changes.
<td align = "right">EMail</td> <html>
<td><input type = "text" name = "EMail" <head>
/></td> <script>
</tr> function storeCookie()
<tr> {
<td align = "right"></td> var pwd =
<td><input type = "submit" value = document.getElementById('pwd').value
"Submit" /></td> document.cookie = "Password=" + pwd +
</tr> ";"
</table> alert("Cookie
</form> Stored\n"+document.cookie);
</body> }
</html> </script>
<script type = "text/javascript"> </head>
<!-- <body>
function validate() { <form name="myForm">
if( document.myForm.Name.value == "" ) Enter Username <input type="text"
{ id="uname"/><br/>
alert( "Please provide your name!" ); Enter Password <input type="password"
document.myForm.Name.focus() ; id="pwd"/><br/>
return false; <input type="button" value="Submit"
} onclick="storeCookie()"/>
if( document.myForm.EMail.value == "" ) <p id="panel"></p>
{ </form>
alert( "Please provide your Email!" ); </body>
document.myForm.EMail.focus() ; </html>
Q] Write a script for creating following Q] Write a JavaScript for creating
frame structure FRUITS, FLOWERS following frame structure: Chapter 1
AND CITIES are links to the webpage and Chapter 2 are linked to the
fruits.html, flowers.html, cities.html webpage Ch1.html and ch2.html
respectively. When these links are respectively. When user click on these
clicked corresponding data appears in links corresponding data appears in
FRAME 3 FRAME3.
<html> Step 1) create file frame1.html
<head> <html>
<title>Frame Demo</title> <body>
</head> <h1 align="center">FRAME1</h1>
<body> </body>
<table border="1"> </html>
<tr> Step 2) create frame2.html
<td align="center" colspan="2"> <html>
FRAME 1 <head>
</td> <title>FRAME 2</title>
</tr> </head>
<tr> <body><H1>Operating System</H1>
<td> <a href="Ch1.html"
FRAME 2 target="c"><UL>Chapter 1</UL></a>
<ul> <br>
<li> <a href=" Ch2.html" target="c"><UL>
<a href="fruits.html" Chapter 2</UL></a>
target="mainframe">FRUITS</a> </body>
</li> </html>
<li> Step 3) create frame3.html
<a href="flowers.html" <html>
target="mainframe">FLOWERS</a> <body>
</li> <h1>FRAME3</h1>
<li> </body>
<a href="cities.html" </html>
target="mainframe">CITIES</a> Step4) create frame_target.html
</li> <html>
</ul> <head>
</td> <title>Create a Frame</title>
<td> </head>
FRAME 3<BR> <frameset rows="30%,*" border="1">
<iframe name="mainframe"></iframe> <frame src="frame1.html" name="a" />
</td> <frameset cols="50%,*" border="1">
</tr> <frame src="frame2.html" name="b" />
</table> <frame src="frame3.html" name="c" />
</body> </frameset>
</html> </frameset>
</html>
Q] Write HTML script that will display }
dropdown list containing options such as </script>
Red, Green, Blue and Yellow. Write a </body>
JavaScript program such that when the </html>
user selects any options. It will change
the background colour of webpage.
Q] Create a slideshow with the group of
<html> three images, also simulate next and
<body> previous transition between slides in
<label for="color">Choose a Background your Java Script.
Color:</label>
<select name="color" id="color" <html>
class="color" onchange="changeColor()"> <head>
<option value="red">Red</option> <script>
<option value="green">Green</option> pics = new Array('1.jpg' , '2.jpg' , '3.jpg');
<option value="blue">Blue</option> count = 0;
<option value="yellow">Yellow</option> function slideshow(status)
</select> {
<script type="text/javascript"> if (document.images)
function changeColor() { {
var color = count = count + status;
document.getElementById("color").value; if (count > (pics.length - 1))
switch(color){ {
case "green": count = 0;
document.body.style.backgroundColor = }
"green"; if (count < 0)
break; {
case "red": count = pics.length - 1;
document.body.style.backgroundColor = }
"red"; documet.imag1.src = pics[count];
break; }
case "blue": }
document.body.style.backgroundColor = </script>
"blue"; </head>
break; <body>
case "yellow": <img src="1.jpg" width="200"
document.body.style.backgroundColor = name="img1">
"yellow"; <br>
break; <input type="button" value="Next"
default: onclick="slideshow(1)">
document.body.style.backgroundColor = <input type="button" value="Back"
"white"; onclick="slideshow(-1)">
break; </body>
} </html>
Q] Write a JavaScript for the folding <li>Nerul</li>
tree menu. <li>Vashi</li>
<html> <li>Panvel</li>
<head> </ul>
<style> </li>
ul, #myUL { </ul>
list-style-type: none; </li>
} </ul>
.caret::before { </li>
content: "\25B6"; </ul>
color: black; <script>
display: inline-block; var toggler =
margin-right: 6px; document.getElementsByClassName("care
} t");
.caret-down::before { var i;
-ms-transform: rotate(90deg); /* IE 9 */ for (i = 0; i < toggler.length; i++) {
-webkit-transform: rotate(90deg); /* toggler[i].addEventListener("click",
Safari */' function() {
transform: rotate(90deg);
} this.parentElement.querySelector(".nested"
.nested { ).classList.toggle("active");
display: none; this.classList.toggle("caret-down");
} });
.active { }
display: block; </script>
} </body>
</style> </html>
</head>
<body> Q] To find the length of the string
<h2>Folding Tree Menu</h2> <html>
<p>A tree menu represents a hierarchical <body>
view of information, where each item can <p id = "result1"> </p>
have a <p id = "result2"> </p>
number of subitems.</p> <script>
<p>Click on the arrow(s) to open or close var str = "hellow world";
the tree branches.</p> document.getElementById("result1").inner
<ul id="myUL"> HTML = "String: " + str;
<li><span class="caret">India</span> var len = str.length;
<ul class="nested"> document.getElementById("result2").inner
<li>Karnataka</li> HTML = "Length: " + len;
<li>Tamilnaadu</li> </script>
<li><span </body>
class="caret">Maharashtra</span> </html>
<ul class="nested">
<li>Mumbai</li>
<li>Pune</li>
<li><span class="caret">Navi
Mumbai</span>
<ul class="nested">
Q] 2 radio buttons to the users for fruits onclick="updateList(this.value)">Fruits
and vegetables and 1 option list. When <input type="radio" name="grp1"
user select fruits radio button option list value=2
should present only fruits names to the onclick="updateList(this.value)">Vegetabl
user & when user select vegetable radio es
button option list should present only <br>
vegetable names to the user. <input name="Reset" value="Reset"
<html> type="reset">
<head> </p>
<title>HTML Form</title> </form>
<script language="javascript" </body>
type="text/javascript"> </html>
function updateList(ElementValue) Q] Write JScript to create pull-down
{ menu with three options [Google,
with(document.forms.myform) MSBTE,Yahoo] once the user will select
{ one of the options then user will be
if(ElementValue == 1) redirected to that site.
{ <html>
optionList[0].text="Mango"; <head>
optionList[0].value=1; <title>HTML Form</title>
optionList[1].text="Banana"; <script language="javascript"
optionList[1].value=2; type="text/javascript">
optionList[2].text="Apple"; function getPage(choice)
optionList[2].value=3; {
} page=choice.options[choice.selectedIndex]
if(ElementValue == 2) .value;
{ if(page != "")
optionList[0].text="Potato"; {
optionList[0].value=1; window.location=page;
optionList[1].text="Cabbage"; }
optionList[1].value=2; }
optionList[2].text="Onion"; </script>
optionList[2].value=3; </head>
} <body>
} <form name="myform" action=""
} method="post">
</script> Select Your Favourite Website:
</head> <select name="MenuChoice"
<body> onchange="getPage(this)">
<form name="myform" action="" <option
method="post"> value="https://www.google.com">Google
<p> </option>
<select name="optionList" size="2"> <option
<option value=1>Mango value="https://www.msbte.org.in">MSBT
<option value=2>Banana E</option>
<option value=3>Apple <option
</select> value="https://www.yahoo.com">Yahoo</
<br> option>
<input type="radio" name="grp1" </form>
value=1 checked="true" </body></html>
Q] Explain getter and setter properties in Java script with suitable example. Property
getters and setters
1. The accessor properties. They are essentially functions that work on getting and setting a
value.
2. Accessor properties are represented by “getter” and “setter” methods. In an object literal
they are denoted by get and set.
let obj = {
get propName() {
// getter, the code executed on getting obj.propName
},
set propName(value) {
// setter, the code executed on setting obj.propName = value
}
};
3. An object property is a name, a value and a set of attributes. The value may be replaced by
one or two methods, known as setter and a getter.
4. When program queries the value of an accessor property, Javascript invoke getter method
(passing no arguments). The retuen value of this method become the value of the property
access expression.
5. When program sets the value of an accessor property. Javascript invoke the setter method,
passing the value of right-hand side of assignment. This method is responsible for setting the
property value.
If property has both getter and a setter method, it is read/write property.
If property has only a getter method , it is read-only property.
If property has only a setter method , it is a write-only property.
6. getter works when obj.propName is read, the setter – when it is assigned.

Example:
<html> set make(newMake) {
<head> this.defMake = newMake;
<title>Functions</title> }
<body> };
<script language="Javascript"> document.write("Car color:" +
var myCar = { myCar.color + " Car Make:
defColor: "blue", "+myCar.make)
defMake: "Toyota", myCar.color = "red";
get color() { myCar.make = "Audi";
return this.defColor; document.write("<p>Car color:" +
}, myCar.color); // red
get make() { document.write(" Car Make:
return this.defMake; "+myCar.make); //Audi
}, </script>
set color(newColor) { </head>
this.defColor = newColor; </body>
}, </html>
Q] Describe, how to read cookie value and write a cookie value. Explain with example.
Web Browsers and Servers use HTTP protocol to communicate and HTTP is a stateless
protocol. But for a commercial website, it is required to maintain session information among
different pages.
Storing Cookies
The simplest way to create a cookie is to assign a string value to the document.cookie object,
which looks like this.
document.cookie = "key1 = value1;key2 = value2;expires = date";
Here the expires attribute is optional. If you provide this attribute with a valid date or time,
then the cookie will expire on a given date or time and thereafter, the cookies' value will not
be accessible.
<html> document.write ("Setting Cookies : " +
<head> "name=" + cookievalue );
<script type = "text/javascript"> }
<!-- //-->
function WriteCookie() </script>
{ </head>
if( document.myform.customer.value == <body>
"" ) { <form name = "myform" action = "">
alert("Enter some value!"); Enter name: <input type = "text" name =
return; "customer"/>
} <input type = "button" value = "Set
cookievalue = Cookie" onclick = "WriteCookie();"/>
escape(document.myform.customer.value) </form>
+ ";"; </body>
document.cookie="name=" + </html>
cookievalue;

Reading Cookies
Reading a cookie is just as simple as writing one, because the value of the document.cookie
object is the cookie. So you can use this string whenever you want to access the cookie. The
document.cookie string will keep a list of name=value pairs separated by semicolons, where
name is the name of a cookie and value is its string value.
You can use strings' split() function to break a string into key and values as follows:-
<html> }
<head> //-->
<script type = "text/javascript"> </script>
<!--
function ReadCookie() </head>
{ <body>
var allcookies = document.cookie;
document.write ("All Cookies : " + <form name = "myform" action = "">
allcookies ) <p> click the following button and see the
cookiearray = allcookies.split(';'); result:</p>
for(var i=0; i<cookiearray.length; i++) { <input type = "button" value = "Get
name = cookiearray[i].split('=')[0]; Cookie" onclick =
value = cookiearray[i].split('=')[1]; "ReadCookie()"/>
document.write ("Key is : " + name + " </form>
and Value is : " + value); </body>
} </html>
Q] Explain open() method of window object with syntax and example
The open() method of window object is used to open a new window and loads the document
specified by a given URL.MyWindow = window.open()The open() method returns a reference
to the new window, which is assigned to the MyWindow variable. You then use this reference
any time that you want to do something with the window while your JavaScript runs.A window
has many properties, such as its width, height, content, and name—to mention a few. You set
these attributes when you create the window by passing them as parameters to the open()
method:
• The first parameter is the full or relative URL of the web page that will appear in the new
window.
• The second parameter is the name that you assign to the window.
• The third parameter is a string that contains the style of the window.We want to open a new
window that has a height and a width of 250 pixels and displays an advertisement that is an
image. All other styles are turned off.
Syntax:
MyWindow = window.open(‘webpage1.html’, 'myAdWin', 'status=0, toolbar=0,
location=0, menubar=0, directories=0, resizable=0, height=250, width=250')
Example:
<html > </script>
<head> </head>
<title>Open New Window</title> <body>
<script > <FORM action=" " method="post">
function OpenNewWindow() { <INPUT name="OpenWindow"
MyWindow = value="Open Window" type="button"
window.open(‘webpage1.html’, onclick="OpenNewWindow()"/>
'myAdWin', 'status=0, toolbar=0, </FORM>
location=0,menubar=0, directories=0, </body>
resizable=0, height=250, width=250') </html>
}

Q] Write JavaScript function that will open new window when the user will clicks on the
button.
<html>
<body>
<button onclick="openWin()">Open "New Window"</button>
<script>
var myWindow;
function openWin()
{
myWindow = window.open("", "myWindow", "width=400,height=400");
myWindow.document.write("<p>Hello Everyone.Welcome to new window.</p>");
}
</script>
</body>
</html>
Q] Describe how to evaluate checkbox selection. Explain with suitable example.
Evaluating Checkbox Selection:
A checkbox is created by using the input element with the type=”checkbox” attribute-value
pair.
A checkbox in a form has only two states(checked or un-checked) and is independent of the
state of other checkboxes in the form. Check boxes can be grouped together under a common
name.
You can write javascript function that evaluates whether or not a check box was selected
and then processes the result according to the needs of your application.
Following example make use of five checkboxes to provide five options to the user regarding
fruit.

<html> }
<head> document.write(x);
<title>HTML Form</title> }
<script language="javascript" }
type="text/javascript"> </script>
function selection() </head>
{ <body>
var x ="You selected: "; <form name="myform" action=""
with(document.forms.myform) method="post">
{ Select Your Favourite Fruits: <br>
if(a.checked == true) <input type="checkbox" name="a"
{ value="Apple">Apple
x+= a.value+ " "; <input type="checkbox" name="b"
} value="Banana">Banana
if(b.checked == true) <input type="checkbox" name="o"
{ value="Orange">Orange
x+= b.value+ " "; <input type="checkbox" name="p"
} value="Pear">Pear
if(o.checked == true) <input type="checkbox" name="g"
{ value="Grapes">Grapes
x+= o.value+ " "; <input type="reset" value="Show"
} onclick="selection()">
if(p.checked == true) </form>
{ </body>
x+= p.value+ " "; </html>
} </form>
if(g.checked == true) </body>
{ </html>
x+= g.value+ " ";
Q] List ways of protecting your web page and describe any one of them.
Ways of protecting Web Page:
1)Hiding your source code
2)Disabling the right MouseButton
3) Hiding JavaScript
4) Concealing E-mail address.
Hiding your source code: The source code for your web page—including your JavaScript—
is stored in the cache, the part of computer memory where the browser stores web pages that
were requested by the visitor. A sophisticated visitor can access the cache and thereby gain
access to the web page source code. However, you can place obstacles in the way of a potential
peeker. First, you can disable use of the right mouse button on your site so the visitor can't
access the View Source menu option on the context menu. This hides both your HTML code
and your JavaScript from the visitor. Nevertheless, the visitor can still use the View menu's
Source option to display your source code. In addition, you can store your JavaScript on your
web server instead of building it into your web page. The browser calls the JavaScript from the
web server when it is needed by your web page. Using this method, the JavaScript isn't visible
to the visitor, even if the visitor views the source code for the web page.
Disabling the right MouseButton: The following example shows you how to disable the
visitor's right mouse button while the browser displays your web page. All the action occurs in
the JavaScript that is defined in the tag of the web page. The JavaScript begins by defining the
BreakInDetected() function. This function is called any time the visitor clicks the right mouse
button while the web page is displayed. It displays a security violation message in a dialog box
whenever a visitor clicks the right mouse button The BreakInDetected() function is called if
the visitor clicks any button other than the left mouse button.
Hiding JavaScript: You can hide your JavaScript from a visitor by storing it in an external fi
le on your web server. The external fi le should have the .js fi le extension. The browser then
calls the external file whenever the browser encounters a JavaScript element in the web page.
If you look at the source code for the web page, you'll see reference to the external .js fi le, but
you won't see the source code for the JavaScript. The next example shows how to create and
use an external JavaScript file. First you must tell the browser that the content of the JavaScript
is located in an external file on the web server rather than built into the web page. You do this
by assigning the fi le name that contains the JavaScripts to the src attribute of the
Concealing E-mail address: Many of us have endured spam at some point and have probably
blamed every merchant we ever patronized for selling our e-mail address to spammers. While
e-mail addresses are commodities, it's likely that we ourselves are the culprits who invited
spammers to steal our e-mail addresses. Here's what happens: Some spammers create programs
called bots that surf the Net looking for e-mail addresses that are embedded into web pages,
such as those placed there by developers to enable visitors to contact them. The bots then strip
these e-mail addresses from the web page and store them for use in a spam attack. This
technique places developers between a rock and a hard place. If they place their e-mail
addresses on the web page, they might get slammed by spammers. If they don't display their e-
mail addresses, visitors will not be able to get in touch with the developers. The solution to this
common problem is to conceal your e-mail address in the source code of your web page so that
bots can't fi nd it but so that it still appears on the web page. Typically, bots identify e-mail
addresses in two ways: by the mailto: attribute that tells the browser the e-mail address to use
when the visitor wants to respond to the web page, and by the @ sign that is required of all e-
mail addresses. Your job is to confuse the bots by using a JavaScript to generate the e-mail
address dynamically. However, you'll still need to conceal the e-mail address in your
JavaScript, unless the JavaScript is contained in an external JavaScript file, because a bot can
easily recognize the mailto: attribute and the @ sign in a JavaScript
Q] write a javascript program to </html>
generate fibonacci series till user defined Q] write a javascript program to convert
limit the given Unicode To character
<html> <html>
<head> <head>
<title> Fibonacci Series in JavaScript </head>
</title> <body>
</head> <p id = "output"> </p>
<body> <script>
<script> let output =
var n1 = 0, n2 = 1, next_num, i; document.getElementById("output");
var num = parseInt (prompt (" Enter the let value = 69;
limit for Fibonacci Series ")); let char = String.fromCharCode( value );
document.write( "Fibonacci Series: "); output.innerHTML += value + " = " + char
for ( i = 1; i <= num; i++) + " <br/> ";
{ document.write (" <br> " + n1); // print char = String.fromCharCode( 97 );
the n1 output.innerHTML += 97 + " = " + char + "
next_num = n1 + n2; // sum of n1 and n2 <br/> ";
into the next_num </script>
n1 = n2; // assign the n2 value into n2 </body>
n2 = next_num; // assign the next_num </html>
into n2
} Q] write a javascript program to validate
</script> email id of the user using regular
</body> expression
</html> <html>
<body>
Q] Write a java script to checks whether <div id = "output"> </div>
a passed string id palindrome or not <button onclick = "validateEmail()">
<html> Validate any email </button>
<head> <title> JavaScript Palindrome <script>
</title> var output =
</head> document.getElementById('output');
<body> function validateEmail() {
<script> let userEmail = prompt("Enter your email.",
function validatePalin(str) { "[email protected]");
const len = string.length; let regex = /^[a-z0-9]+@[a-z]+\.[a-
for (let i = 0; i < len / 2; i++) { z]{2,3}$/;
if (string[i] !== string[len - 1 - i]) { let result = regex.test(userEmail);
alert( 'It is not a palindrome'); if (result) {
} output.innerHTML = "The " + userEmail +
} " is a valid email address!";
alert( 'It is a palindrome'); } else {
} output.innerHTML = "The " + userEmail +
const string = prompt('Enter a string or " is not a valid email address!";
number: '); }
const value = validatePalin(string); }
console.log(value); </script>
</script> </body>
</body> </html>
Q] write a javascript program to create d) Develop JavaScript to convert the
read update and delete cookies given character to Unicode and vice
<html> versa.
<head> <html>
<script> <head>
function setCookie(cname,cvalue,exdays) <script type="text/javascript">
{ function charToUnicode()
const d = new Date(); {
d.setTime(d.getTime() + var text =
(exdays*24*60*60*1000)); document.getElementById("text").value;
let expires = "expires=" + d.toUTCString(); var result="";
document.cookie = cname + "=" + cvalue + for(var i=0; i<text.length; i++)
";" + expires + ";path=/"; {
} result += "\\u" +
function getCookie(cname) { text.charCodeAt(i).toString(16);
let name = cname + "="; }
let decodedCookie =
decodeURIComponent(document.cookie); document.getElementById("result").value
let ca = decodedCookie.split(';'); =result;
for(let i = 0; i < ca.length; i++) { }
let c = ca[i]; function unicodeToChar()
while (c.charAt(0) == ' ') { {
c = c.substring(1); var code =
} document.getElementById("code").value;
if (c.indexOf(name) == 0) { var result = "";
return c.substring(name.length, c.length); for(var i=0; i<code.length; i+=4)
} {
} result +=
return ""; String.fromCharCode(parseInt(code.substr
} (i, 4), 16));
Aditi Gharat
function checkCookie() { }
let user = getCookie("username");
if (user != "") { document.getElementById("result2").valu
alert("Welcome again " + user); e=result;
} else { }
user = prompt("Please enter your </script>
name:",""); </head>
if (user != "" && user != null) { <body>
setCookie("username", user, 30); <h1>Character to Unicode Converter</h1>
} <input type="text" id="text" />
} <input type="button" value="Convert"
} onclick="charToUnicode()" />
</script> <input type="text" id="result" />
</head> <h1>Unicode to Character Converter</h1>
<body onload="checkCookie()"></body> <input type="text" id="code" />
</html> <input type="button" value="Convert"
onclick="unicodeToChar()" />
<input type="text" id="result2" />
</body></html>
Q] 2 FRAME (S22) Q]fruits, flowers and cities Q] OSY ch1,ch2 frame
<html> when these links are Step1)create file
<frameset clicked data appears in frame1.html
cols="25%,75%"> frame 3 <html>
<frame <html> <body>
src="file:///C:/Users/shma <head> <h1
te/Desktop/css/frame1.ht <title>Frame align="center">FRAME1
ml" name="frame1"/> Demo</title> </h1>
<frame </head> </body>
src="file:///C:/Users/shma <body> </html>
te/Desktop/css/ <table border="1"> Step 2) create frame2.html
/frame2.html" <tr> <html>
name="frame2"/> <td align="center" <head>
</frameset> colspan="2"> <title>FRAME 2</title>
</html> FRAME 1 </head>
Framel htmle= </td> <body><H1>Operating
<html> </tr> System</H1>
<body> <tr> <a href="Ch1.html"
<h4>Open Image</h4> <td> target="c"><UL>Chapter
<ul> FRAME 2 1</UL></a><br>
<a <ul> <a href=" Ch2.html"
href="file:///C:/Users/shm <li> target="c"><UL> Chapter
ate/Desktop/css/picture1. <a href="fruits.html" 2</UL></a>
html" target="frame2"> target="mainframe">FRU </body>
<input ITS</a> </html>
type="button"va="Check" </li> Step 3) create frame3.html
/> <li> <html>
</a> <a href="flowers.html" <body>
</ul> target="mainframe">FLO <h1>FRAME3</h1>
</body> WERS</a> </body>
</html> </li> </html>
Frame2.html= <li> Step4) create
<html> <a href="cities.html" frame_target.html
<head> target="mainframe">CITI <html>
</head> ES</a> <head>
<body> </li> <title>Create a
<h4>Frame 2</h4> </ul> Frame</title>
</body> </td> </head>
</html> <td> <frameset rows="30%,*"
picture1.html= FRAME 3<BR> border="1">
<html> <iframe <frame src="frame1.html"
<head> name="mainframe"></ifr name="a" />
</head> ame> <frameset cols="50%,*"
<body> </td> border="1">
<h4>Image</h4> </tr> <frame src="frame2.html"
<img </table> name="b" />
src='file:///E:\\Javascript\\ </body> <frame src="frame3.html"
images\\apple.jpg'> </html> name="c" />
</body> </frameset>
</html> </frameset></html>
alert box prompt box
An alert box is used if we want the A prompt box is used when we want the
information comes through to the user. user to input a value before entering a
page.
Its syntax is -: Its syntax is
window.alert(“sometext”); window.prompt(“sometext”,”default
Text”);
It always return true we always need to We need to click “OK” or “Cancel” to
click on “OK” to proceed further. proceed after entering an input value
when a prompt box pops up on a
webpage.
The alert box takes the focus away from If we click “OK” the box returns the
the current window and forces the input value.
browser to read the message.
We need to click “OK” to proceed when If we click “Cancel” the box returns a
an alert box pops up. null value.
Example: <html>
<html> <script type="text/javascript">
<script type="text/javascript"> function msg(){
function msg(){ var v= confirm("Are u sure?");
var v= prompt("Who are you?"); if(v==true){
alert("I am "+v); alert("ok");
} }
</script> else{
<input type="button" value="click" alert("cancel");
onclick="msg()"/> }
</html }
</script>
<input type="button" value="delete
record" onclick="msg()"/>
</html>

concat() join()
The concat() method concatenates The join() method returns an array as a
(joins) two or more arrays. string
The concat() method returns a new
array, containing the joined arrays.
The concat() method separates each Any separator can be specified. The
value with a comma only. default is comma (,).
Syntax: array1.concat(array2, array3, ..., Syntax: array.join(separator)
arrayX)
Example: Example:
<script> <script>
const arr1 = ["CO", "IF"]; var fruits = ["Banana", "Orange",
const arr2 = ["CM", "AI",4]; "Apple", "Mango"];
const arr = arr1.concat(arr1, arr2); var text = fruits.join();
document.write(arr); document.write(text);
</script> var text1 = fruits.join("$$");
document.write("<br>"+text1);</script>
Aspect for Loop for...in Loop
Purpose Used for iterating over arrays Used for iterating over
or specified iterations enumerable properties of an
object
Syntax for (initialization; condition; for (variable in object)
increment/decrement) { // code { // code }
}
Iterates Array elements or specified Object properties
Over iterations
Use Case When the number of iterations When looping through object
is known or for arrays properties is required
Control Allows precise control over the Less control as it iterates
loop execution through object properties
Example javascript for (let i = 0; i < 5; javascript for (let prop in
i++) { // code } object) { // code }

Aspect Session Cookies Persistent Cookies


Lifespan Exist for the duration of the Have an expiration date set for
browsing session future sessions
Duration Deleted when the browser is Can persist beyond the current
closed browsing session
Usage Temporary storage, Storing information needed
maintaining user sessions across multiple visits/sessions
Deletion Automatically deleted when Remain until expiration date or
the browser is closed manually deleted
JavaScript javascript document.cookie = javascript document.cookie =
Syntax "name=value; path=/"; "name=value; expires=date;
(without setting expiration) path=/"; (with expiration)

Aspect setInterval() setTimeout()


Execution Repeatedly executes code at Executes code once after a
set intervals. delay.
Usage setInterval(callbackFunction, setTimeout(callbackFunction,
delay) delay)
Repeated Calls Continues until explicitly Executes only once unless re-
stopped with clearInterval(). called with setTimeout()
again.

Stopping Requires clearInterval() to Executes once unless


stop execution. canceled by clearTimeout().
Example setInterval(function, 1000) setTimeout(function, 2000)

You might also like