You are on page 1of 58

I.

BASIC OF JAVASCRIPT

Q1. Introduction to JAVASCRIPT?


Ans.:
 It was developed by Brendan Eich in 1995. It was initially called
LiveScript and was later renamed to JavaScript.
 JavaScript code are placed inside <script> tag.
 JavaScript are case sensitive.
Q2. STATEMENT AND COMMENT?
Ans.:
 HELLOWORLD IN JAVASCRIPT
<script type=”type/javascript”>
document.write(“HELLO WORLD.”);
</script>
 /* c0mment in javascript */
Q3. Type of popup box?
Ans.:
 Alert Box –
o An alert dialog box is mostly used to give a warning message
to the users.

<BUTTON onclick="myFunction()")>CLICK </BUTTON>


<p id="demo"></p>
<script>
function myFunction() {
alert("I am an alert box!");
}
</script>
O/P –
 Confirm Box –
o A confirmation dialog box is mostly used to take user's
consent(permission) on any option. It displays a dialog box
with two buttons: OK Cancel.
 OK button - the window method confirm() will return
true.
 Cancel button - then confirm() returns false.
<BUTTON onclick="myFunc()")>CLICK </BUTTON>
<p id="demo"></p>
<script>
function myFunc()
{
var txt;
if(confirm("Press OK button.")) //TRUE
{
txt = "You pressed OK!";
}
else //FALSE
{
txt = "You pressed CANCEL!";
}
document.getElementById("demo").innerHTML = txt;
}
</script>
O/P – Press OK

O/P – Press Cancel


 Prompt Box –
o The prompt dialog box is very useful when you want to pop-
up a text box to get user input. Thus, it enables you to
interact with the user. The user needs to fill in the field and
then click OK.
o prompt dialog box has two buttons –
 OK – Return text entered into the textbox
 CANCEL - Return null
<BUTTON onclick="myFunc()")>CLICK </BUTTON>
<p id="demo"></p>
<script>
var txt;
var person = prompt("Please enter your name", "Prashant");
if(person == null || person == "")
{
txt = "User cancelled the Prompt.";
}
else
{
txt = "Hello " + person + "! How are you today?";
}
document.getElementById("demo").innerHTML = txt;
</script>
O/P -
Q4. Variable in javascript?
Ans.:
 var
o var stands for variable.
o JavaScript variables are containers for storing data values.
o In C#, we have used data type like int, string, float to store a
values relates to it, on the other hand javascript use var to
store all kind of data
o E.G. –
var x = 5;
var pi = 3.14;
var person = "John Doe";
var answer = 'Yes I am!';
 Difference between let and var
o var is used to declare a global variable
o let is used to declare a variable whose scope is limited to a
block. So when you declare a variable using let in an if block
and its scope is limited to that block
Q5. OPERATOR
Ans.:
 The following are the operators –
o +, -, *, /, =, >, < …etc
Q6. CONCATENATE
Ans.:
<script>
var txt;
var msg1 = "abc";
var msg2 = "efg";
document.write(msg1 + msg2);
</script>

O/P –
Abcefg
Q7. Console.Log –
 Console.Log –
o The console.log() method writes a message to the console.
o The console is useful for testing purposes.
o Syntax –
console.log(message);
message is a parameter of type String or Object.
o E.g.1 – Hello World Console log
console.log("Hello world!");

Q9. parseInt -
Ans.:
 By default variable store values in string format. To assign a var
holding a integer, it need to be converted first to integer.
var x = 100;
var y = parseInt(x);
Q8. EXAMPLE –
Ans.:
 E.G.1- Take input from user and display on browser
<html>
<head>
<title>Example of javascript</title>
<script language="javascript">
var name;
var age;
var qualification;
var salary;

name = (prompt("Enter Your Name : ","Type your name here..."))


age = parseInt(prompt("Enter your age : ","Type your age here..."))
qualification = (prompt("Enter your qualification : ", "Type your qualification here..."))
salary = parseInt(prompt("Enter your salary", "Type your salary here..."))

document.write("<b>Your name is : </b>"+"<i>"+name + "</i>"+"<br>");


document.write("<b>Your Age is :</b>"+"<i>"+age+"</i>"+"<br>")
document.write("<b>Your Qualification is :</b>"+"<i>"+qualification+"</i>"+"<br>")
document.write("<b>Your Salary is :</b>"+"<i>"+salary+"</i>"+"<br>")
</script>
</head>
<body>
<h1>EXAMPLE 1</h1>
</body>
</html>
 E.G. 2 – Take input from user, calculate and display on browser
<html>
<head>
<title>Example of javascript</title>

<script language="javascript">
var num1;
var num2;

num1 = parseInt(prompt("Enter Number 1 : ", "Type here ..."));


num2 = parseInt(prompt("Enter Number 1 : ", "Type here ..."));

add = num1 + num2;


sub = num1 - num2;
mul = num1 * num2;
div = num1 / num2;
mod = num1 % num2;

document.write("<b>Addition of Two Number : </b>"+"<i>"+add+"</i>"+"<br>")


document.write("<b>Subtraction of Two Number : </b>"+"<i>"+sub+"</i>"+"<br>")
document.write("<b>Multiplication of Two Number : </b>"+"<i>"+mul+"</i>"+"<br>")
document.write("<b>Divsion of Two Number : </b>"+"<i>"+div+"</i>"+"<br>")
document.write("<b>Modlus of Two Number : </b>"+"<i>"+mod+"</i>"+"<br>")

</script>
</head>
<body>
<h1>EXAMPLE 1</h1>
</body>
</html>
O/P -
 E.G. 3 – Conditional if…else
<html>
<head>
<title>Example of javascript</title>

<script language="javascript">
var num;
num = 100;
if(num<=100)
{
document.write("Number is less than or equal to 100");
}
</script>
</head>
<body>
<h1>EXAMPLE</h1>
</body>
</html>.

 E.G. 4 – if..else addition, subtraction,…etc


<html>
<head>
<title>Example of javascript</title>
</head>
<body>
<h1>EXAMPLE</h1>

<script language="javascript">
var num1, num2, add, sub, mul, div, res;
num1 = parseInt(prompt("Enter number 1","enter number between 1-50"));
num2 = parseInt(prompt("Enter number 2","enter number between 1-50"));

res = parseInt(prompt("Enter your choice - 1. Addition 2. Subtraction 3. Multiplication


4. Division"))

if(res==1)
{
add = num1 + num2;
document.write("Addition of two number is "+add);
}
else if(res==2)
{
sub = num1 - num2;
document.write("Subtraction of two number is "+sub);
}
else if(res==3)
{
mul = num1 * num2;
document.write("Multiplication of two numbwe is "+mul);
}
else if(res==4)
{
div = num1 / num2;
document.write("Division of two numbwe is "+div);
}
</script>

</body>
</html>

O/P –
 E.G. 5 – Switch Case (find entered character is a vowel)
<html>
<head>
<title>Example of javascript</title>
</head>
<body>
<h1>EXAMPLE</h1>

<script language="javascript">
var choice;
choice = (prompt("Enter a character of your choice -"))
choice = choice.toUpperCase();

debugger
switch(choice){
case 'A': document.write('The charater you entered is a vowel');
break;

case 'E': document.write('The charater you entered is a vowel');


break;

case 'I': document.write('The charater you entered is a vowel');


break;

case 'O': document.write('The charater you entered is a vowel');


break;

case 'U': document.write('The charater you entered is a vowel');


}
</script>

</body>
</html>.

 E.G. 6 – FIND ENTER NUMBER IS PRIME


<html>
<head>
<title>Example of javascript</title>
</head>
<body>
<h1>EXAMPLE</h1>

<script language="javascript">
var inpNum = prompt("Enter number","type here");
inpNum = parseInt(inpNum);
var num = 2;
while(num<=inpNum-1)
{
if(inpNum%num == 0){
document.write(inpNum+" is not a prime number.");
break;
}
num++;
}
if(num==inpNum){
document.write(inpNum + " is a prime number.");
}
</script>
</body>
</html>

E.G. 7 – BREAK AND CONTINUE EXAMPLE -


BREAK - The break statement breaks the loop

<html>
<body>

<p>A loop with a break.</p>

<p id="demo"></p>

<script>
var text = "";
var i;
for (i = 0; i < 10; i++) {
if (i === 3) { break; }
text += "The number is " + i + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

O/P –

A loop with a break.

The number is 0
The number is 1
The number is 2

 CONTINUE –

E.G. 8 –

<html>
<body>

<p>A loop which will skip the step where i = 3.</p>

<p id="demo"></p>

<script>
var text = "";
var i;
for (i = 0; i < 10; i++) {
if (i === 3) { continue; }
text += "The number is " + i + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

O/P –

A loop which will skip the step where i = 3.

The number is 0
The number is 1
The number is 2
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9
 FOR IN
o Used with array - Execute each element of an array.
o Used with object – Execute one or more statements for each
property of an object.
o Syntax –
for (variable in [object | array]) {
statements
}

 variable –
 name of variable
 object/ array –
 An object or array over which to iterate.
 statement –
 One or more statement to be executed for each
property of object or each array.
 E.G. 9 -
<html>
<head>
<title>Example of javascript</title>
</head>
<body>
<h1>EXAMPLE</h1>

<script language="javascript">
a = {"a":"Alpha", "b":"Beta", "c":"Charlie"};

var s = ""
for(var key in a){
s += key + ": " + a[key];
s += "<br/>";
}

document.write(s);
</script>
</body>
</html>.

O/P –
 E.G. 10 -
<html>
<head>
<title>Example of javascript</title>
</head>
<body>
<h1>EXAMPLE</h1>

<p id="demo"></p>
<script language="javascript">
function myFunc(){
var person = {fname: "John", lname:"Doe", age:"25"};

var text = "";


var x;
//display properties
for(x in person){
text += person[x] + " ";
}
document.getElementById("demo").innerHTML = text;
}
</script>
</body>
</html>.

O/P -
Q8. EVENT
Ans.:
 abort
 blur
 click
 change
 error
 focus
 load
Resource - http://eloquentjavascript.net/01_values.html
We will discuss about it in more detail
Q9. VALUES
Ans.:
 VALUES IN JAVASCRIPT –
o Value takes space in memory.
o There are four types of values in javascript -
 numbers
 string
 Boolean
 Undefined values
Q9. Airthmethic operation
o Airthmethic operation in javascript -
 Operator in airthmethic operation
 + ;- Addition
 - ; - Subtraction
 * ;- multiplication
 / ;- division
 Precedence of airthmethic operation –
 (*, /) has same precedence
 (+, - )has same precedence
 (*, /) comes first before (+,-) in precendence
 We can use precedence operator to change precedence.
 % - x%y –
 Finds remainder.
 E.g. –
o 144%12 gives 0
o Other value -
 Positive Infinity and negative Infinity
 E.g. –
0/0
 NaN – Not A Number
o String –
 Use double and Single quote
 E.g. 1 –
"Lie on the ocean"
`Down on the sea`
 E.g. 2 –
\n – new line character

"This is the first line\nAnd this is the second"

It displayed in below manner –


This is the first line
And this is the second
 String in javascript are represented by Unicode
standards. i.e Assigning a string virtually means
assigning a number pattern.
o Concatenate –
 String can be added, this will concatenate string.
 E.g.
‘Abc ‘+ ‘efg’

O/P –
Abcefg
o Using String and Number together –
 ${ } is called as template literal.
 E.g. –
`half of hundred is ${100/2}`

half of hundred is 50
o Unary Operator –
 typeof operator –
e.g.1 –
console.log(typeof 4.5)
O/p
number

e.g.2 –
console.log(typeof "x")
O/p
string

Q10 Programming Structure in javascript


Resource -
http://eloquentjavascript.net/02_program_structure.html
Ans.:
 Expression –
o A code that produce a value is called as ‘Expression’.
 PromptBox
<html>
<head></head>
<body>
<script>
prompt("Enter Password")
</script>
</body>
</html>

o E.g. 2 – Display firstname and lastname


<script >
var myObj = { firstname : "John", lastname : "Doe" };
console.log(myObj);
</script>
O/P –
o E.g. 3 – Display greater number from 2
<script>
console.log(Math.max(2,4));
</script>

o E.g. 4 – Display minimum number from 2


<script>
console.log(Math.min(2,4));
</script>
O/p –
2

 If … Else -
o E.g.1–

<script>
num = Number(prompt("pick the number"));
if(!Number.isNaN(num))
{

console.log("Your number is "+num * num);


}
else
{
console.log("please input some number");
}
</script>

 O/P –

After Clicking on OK

Q11. FUNCTION
RESOURCES – http://eloquentjavascript.net/03_functions.html
 Syntax
function functionName(parameters) {
    code to be executed
}
 const –
o Are aka constant.
o Values assigned to constant cannot be changed.

 E.G. 1 – A simple example of function


o CODE 1 -
<p id="demo"></p>
<script>
function myFunc()
{
document.getElementById("demo").innerHTML =
"Hello World!";
}
myFunc();
</script>

o CODE 2 -
<p id="demo"></p>
<BUTTON ONCLICK=msg()>CLICK </BUTTON>
<script>
function msg()
{
document.getElementById("demo").innerHTML = "HELLO
FROM FUNCTION";
}
</script>
O/P –

CLICK ON BUTTON TO SEE THE MESSAGE

 E.G. 2 – display value of pi (3.14) in Math, using function.


<p id="demo"></p>
<script>
function myFunc()
{
return Math.PI;
}
document.getElementById("demo").innerHTML = myFunc();
</script>

O/P -

 E.g. 3 – Pass value to function parameter


o Code 1 – a simple way
<p id="demo"></p>
<script>
function myFunc(a,b)
{
return a * b;
}
document.getElementById("demo").innerHTML = myFunc(12, 12);
</script>
O/P -

o Code 2 – using button click –


<p id="demo"></p>
<BUTTON onclick="msg()">CLICK </BUTTON>
<script>
var z = msg(12,12);
function msg(x,y)
{
document.getElementById("demo").innerHTML = z;
return x+y;
}
</script>

 E.g. 4 – Pass argument to parameter


Celsius to fahrenheit
<p id="demo"></p><p>CELSIUS</p>
<script>
function toCelsius(fahrenheit)
{
return (5/9) * (fahrenheit-32);
}
document.getElementById("demo").innerHTML = toCelsius(60);
</script>

O/P -

o Code 3 – remove undefined –


Use not null
 Note –
 To Check undefined we can write
o If(x===undefined){}
 To Check undefined we can write
o If(x==!undefined){}
 To Check Not null we can write
o If(!!x){}
SOLUTION –
<p id="demo"></p>
<BUTTON onclick="celsi(100)">CLICK </BUTTON>
<script>
var temprature;
function celsi(fahrenheit)
{
celsius = (5/9) * (fahrenheit-32);
if(!!celsius)
{
document.getElementById("demo").innerHTML = celsius;
}
}
</script>

 E.G. 6 – assign function to a variable


o Code 1 -
<p id="demo"></p>
<script>
var x = function (a,b)
{
return (a * b)
};
document.getElementById("demo").innerHTML = x(4,3);
</script>

O/P –
12

o Code 2 – PASSING ARGUMENT TO PARAMETER


THROUGH TEXTBOX
Enter Base - <input type="text"
id="base"></input><br/><br/>
Enter Exponent - <input type="text"
id="exponent"></input><br/><br/>
<BUTTON onclick = " power(document.getElementById
('base'). value, document.getElementById('exponent').value)">

CLICK </BUTTON><p id="demo"></p>


<script>
debugger;
const power = function(base, exponent)
{
let result = 1;
for(let count=0; count<exponent; count++)
{
result *= base;
}
document.getElementById("demo").innerHTML=result;
};
</script>

o Code 3 – PASSING ARGUMENT TO WITHOUT USING


PARAMETER THROUGH TEXTBOX – 2nd Way
Enter Base - <input type="text"
id="base"></input><br/><br/>
Enter Exponent - <input type="text"
id="exponent"></input><br/><br/>

<BUTTON onclick="power()">CLICK </BUTTON>


<p id="demo"></p>
<script>
debugger;
const power = function()
{
var base = document.getElementById('base').value;
var exponent =
document.getElementById('exponent').value;
let result = 1;
for(let count=0; count<base; count++)
{
result *= exponent;
}
document.getElementById("demo").innerHTML=result;
};
</script>

 E.G. 7 - arguments.length;
Return nos. of arguments
function myFunction(a, b) {
    return arguments.length;
}

Q12. DATA STRUCTURE –


 There are four types of data -
o NUMBER,
o BOOLEAN,
o STRING,
o OBJECT

 OBJECT IN JAVASCRIPT –
o Javascript supports OOPS concept. It has four basic
capabilities -
 Encapsulation -
 Store related information together in an object.
 Aggregation -
 Store one object inside another object.
 Inheritance
 Capabilities of a class to rely upon another class.
 Polymorphism
 Capability of function or method to work in
different ways.

 PROPERTIES –
o Properties are the values associated with a JavaScript object.
o Properties can usually be changed, added, and deleted, but
some are read only.
o Declaring a properties –

objectName.propertyName

o PROPERTY ACCESSORS -
 There are two ways to access properties of object using
dot(.) and Square brackets.
 value.x and value[x] -
o In above expression, the difference is in how
x is interpreted.
o Dot notation are most widely used. Dot
notation are much easier to read than
bracket notation.
o .(dot) - declare a property
 objectName.propertyName;
 value.x
 E.g. 1 – declare a property
var obj = {
//obj_name = properties
Cat: ‘meow’,
Dog: ‘woof’
};
Cat is a name of an object, meow is its
properties.
 . is used to declare a property.

o [ ] (square brackets) –
 objectName["propertyName"]
E.g. 1 – access a property
var sound = obj[‘cat’];
O/P –
meow
 value[x]
 Expression between brackets are
evaluated.
 [] is used to access a property.
 Properties can be user defined or it can be pre-defined.
 Predefined properties are as follows –
 myString.length - to get the length of a string
 Math.max – find greatest number
 name
 User defined properties -
 E.G.1 – Following example shows user defined
data type -
<html>
<body>

<p id="demo"></p>

<script>
var person = new Object();
person.firstName = "John";
person.lastName = "Doe";
person.age = 50;
person.eyeColor = "blue";

document.getElementById("demo").innerHTML
=
person.firstName + " is " + person.age + " years
old.";
</script>

</body>
</html>

O/P-
John is 50 years old.
 E.G. 2 –

var myCar = new Object();


myCar.make = 'Ford';
myCar.model = 'Mustang';
myCar.year = 1969;

o Unassigned properties of an object are known as


undefined (and not null).
 E.g. – undefined properties

var myCar = new Object();


myCar.make; //undefined
myCar.model; //undefined
myCar.year = 1969;

o Object.key –
 To find out what properties an object has, you can
use Key function
console.log(Object.keys({x: 0, y: 0, z: 2}));
// → ["x", "y", "z"]
o Object.assign –
 To copy properties of one object to another object
we us assign function,
let objectA = {a: 1, b: 2};
Object.assign(objectA, {b: 3, c: 4});
console.log(objectA);
// → {a: 1, b: 3, c: 4}

o Object.delete –
 To delete properties of one object we use delete
function,
let anObject = {left: 1, right: 2};
console.log(anObject.left);
// → 1
delete anObject.left;
console.log(anObject.left);
// → undefined
console.log("left" in anObject);
// → false
console.log("right" in anObject);
// → true
o Compare object with properties –
E.g. 1 -
const score = {visitors: 0, home: 0};
score.visitors = 1;
score is a name of variable. Visitor is name of a property.
To change the property value we can do this -
(score.visitors = 1;)

 METHOD –
o JavaScript methods are the actions that can be performed on
objects.
o Methods are like inbuilt or predefined functions which act as
a properties for object.
Syntax -
objectName.methodName()
o This –
 this is a Keyword
 this refer to object
 E.g.1 - this refer to object person
var person = {
fname : "John",
lname : "Doe",
id : 5566,
fullName : function(){
return this.fname + "" + this.lname;
In the above e.g. this refers to Object person

 Note that this is not a variable. It is a keyword. You


cannot change the value of this.
o E.g.1 – user defined method
<html>
<body>
<p id="demo"></p>
<script>
var person = {
fname : "John",
lname : "Doe",
id : 5566,
fullName : function(){
return this.fname + "" + this.lname;
}
};

document.getElementById("demo").innerHTML =person.fullName();
</script>
</body>
</html>

O/P –

o E.g.2 – Pre-defined method


<html>
<body>
<p id="demo"></p>
<script>
var msg = "Hello World!.";
var x = msg.toUpperCase();

document.getElementById('demo').innerHTML = x;

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

O/P -
o E.g.3 –
This example demonstrate use of method like push and pop.
Both this method are used with array and stack.
 push - add new value to array or stack
 pop – remove last value from array or stack
<html>
<body>
<p id="demo"></p>
<script>
var sequence = [1,2,3];
sequence.push(4);
sequence.push(5);

document.getElementById("demo").innerHTML = sequence;
</script>
</body>
</html>

O/P –

 JAVASCRIPT OBJECT –
o JavaScript is based on object paradigm. An object is a
collection of properties, a property is an association between
a name (or key) and a value.
o Declare a new object –
 Var ObjectName = New Object();

o User defined object


 JavaScript methods are the actions that can be
performed on objects.
 E.G.
<p id="demo"></p>

<script>
var person = new Object();
person.firstName = "John";
person.lastName = "Doe";
person.age = 50;
person.eyeColor = "blue";

document.getElementById("demo").innerHTML =
person.firstName + " is " + person.age + " years old.";
</script>

O/P-
John is 50 years old.

o Javascript object
 Array object
 Boolean object
 Date object
 Enumerator object
 Math object
 Number object
 String object
 JSON object
 RegEx

o Object are of four types –


 User defined object –
 new Operator
 Object Constructor
Q3. var, let, const

Q3 What IS JAVASCRIPT?
Ans.:
1. JavaScript JS, is a 
high-level, :
 High Level language has less code more ouput, such type of
language use OOP concept.
 A prog. Lang. with strong abstraction from details of code.
 Unlike c. c++ which is a low level language, which do no haves
intellisense, GUI

dynamic, 
 Dynamic code execute at runtime instead of compile time.
weakly typed, 
 Strongly type has strict typing rule.
 But not in case of weakly type.
prototype-based, 
 Means JS support OOP Concept
2. ADVANTAGE –
a. It is used to make webpages interactive and provide online
programs, including video games. 
b. Create a modern webpages.
c. It has an API for working with text, arrays, dates, regular
expressions… etc.

Q2. HTML DOM?


Ans.:
 DOM stands for Document Object Model
 When a web page loads on browser, it creates
a Document Object Model of the page.
 Document Object Model of the page look like this -

 What is the HTML DOM?


o The HTML DOM is a standard object model
and programming interface for HTML. It defines:

 The HTML elements as objects -


o E.g. - <h1></h1>, <a></a> <div></div>…etc.
are html object.
 The properties of all HTML elements -
o accessKey – press w to call some event
 E.g.

document.getElementById("myAnchor").accessKey = "w";

o class =”abc”
 E.g. call a class at button click
https://www.w3schools.com/jsref/tryit.asp?
filename=tryjsref_element_classname
<style>
.mystyle {
width: 300px;
height: 100px;
background-color: coral;
text-align: center;
font-size: 25px;
color: white;
margin-bottom: 10px;
}
</style>

<body>
<button onclick="myFunction()">Try
it</button>

<script>
function myFunction() {
document.getElementById("myDIV").className = "mystyle";
}
</script>
<body>

o focus

<input type="button" onclick="getfocus()" value="Get focus">


<input type="button" onclick="losefocus()" value="Lose focus">

<script>
function getfocus() {
document.getElementById("myAnchor").focus();
}
function losefocus() {
document.getElementById("myAnchor").blur();
}
</script>

o Id=”xyz”
o innerHtml
o innerText
 The methods to access all HTML elements -
o After
 E.g.

$("button").click(function(){
    $("p").after("<p>Hello world!</p>");
});

o Height –
 E.g. –

$("button").click(function(){
    alert($("div").height());
});

https://www.w3schools.com/jsref/dom_obj_all.asp

 The events for all HTML elements -


o E.g.

<button onclick="displayDate()">Try it</button>

o E.g.

<body>

<h1 onclick="changeText(this)">Click on this text!</h1>

<script>
function changeText(id) { 
    id.innerHTML = "Ooops!";
}
</script>
</body>

We will look at method ,properties and event in more detail in next


section.

Q3. What is document.getElementById("demo").innerHTML?


Ans:-
 CODE –
<html>
<body>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = "Hello World!";
</script>

</body>
</html>
O/p –

Hello World!

 OBJECT
o Note – resources –
https://chortle.ccsu.edu/java5/Notes/chap25/ch25_5.html
o What is Object?
 In S/W object are similar to real world object, object in
s/w are inspired from real world.
 We can see, touch, interact with object
 An object has a
 Property – color, font, size, location
 Method –
o Method is a Behaviour of object
 Main() –
 Default behaviour of object.
 entry for all other method
 Move()
 Resize()
 Exit()
 Event–
o Call a function on click button, or selecting
radio button, check box, or when user
perform some event on website.
 DOM –
o It stands for Document object model.
o When a web page loads on browser, it creates
a Document Object Model of the page.
o Document Object Model of the page look like this -

 document
o document is an Object.
o Similarly, web page is also an object, that represent the
HTML document displayed on browser window.
o In the HTML DOM (Document Object Model), everything is
a node:
 Nodes –
 All the points on the line nodes. Nodes are
moving in a line one after another.

 Document –
 document itself is a document node.
 The document object is the root node of the
HTML document and the "owner" of all other
nodes.

 element - all html elements are element nodes


 attribute - all html attributes are attribute nodes
 text - Text inside HTML elements are text nodes
 Comments - Comments are comment nodes
 document.getElementById
o getElementById =
 It is similar to find a keyword id in document.
(find a keyword in pdf or msoffice) and it point to an Id.

 E.g.:
<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = "Hello
World!";
</script>
Above e.g. shows document.getElementById… Point to id demo.
 innerHTML 
o it is a property used to get or replace the content of id with
another content.
o E.g. In above e.g. getelementById search for id=demo, and
replace the content present in it with HelloWorld.

Q4. STRING
Ans.:
 Strings are object.
 You can use single or double quotes:
o E.g.1 –
<body>
<p id="demo">ABC EFG HIJ SOME CONTENT</p>

<script>
var x = new String("My name is 'Prashant'");
document.getElementById("demo").innerHTML = x;
</script>
</body>
o E.g.2 –
<body>
String - <p id="demo">ABC EFG HIJ SOME CONTENT</p>
Length - <p id="demo_length"></p>
<script>
var x = new String("My name is 'Prashant'");
var y = x.length;
document.getElementById("demo").innerHTML = x;
document.getElementById("demo_length").innerHTML = y;
</script>
</body>

O/P –

 Escape Sequence in javascript –


o Escape sequence are non printable character like \
(backslah), \n(new line) \r(carriage return) … etc are
combined with other characters, to create output as expected.

o PROBLEMS -
 E.g. 1 - display string
<body>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
"We are "Vikings".";
</script>
</body>
O/p –
(-no output-)
SOLUTION –
document.getElementById("demo").innerHTML = "We
are \"Vikings\".";
O/P –
We are "Vikings".
o E.g. 2 - Concatenate the two strings to display "Hello
World!".
<p id="demo">Display the result here.</p>

<script>
var str1 = "Hello ";
var str2 = "World!";
</script>
O/P –
Display the result here.
 We already discussed that string and object in previous section.
Now we knew that object has some properties, method. So the
string does have properties and methods.
o Properties –
 Length –
 get the length of string.
 We already practised example of length in our
previous section.
o Method –
 String –
 E.g. –
<button onclick="myFunc()">Click</button>
<p id="demo">ABC EFG HIJ SOME CONTENT</p>

<script>
function myFunc()
{
var x = new String("My name is 'Prashant'");
var y = x.toString();
document.getElementById("demo").innerHTML = x;
}
</script>
Q3. More use document.getElement…
And innerHtml? With E.g.
Ans.:
Similarly we have

Method Description
document.getElementById(id) Find an element by
element id
document.getElementsByTagName(name) Find elements by tag name

document.getElementsByClassName(name Find elements by class


) name. Allow Effect on
multiple element.

E.g.1 -document.getElementByTagName(name)
<html>
<head></head>
<body>
<ul>
<li>one </li>
<li>two </li>
<li>three </li>
</table>
<button onclick="myfunc()">Click To change table data</button>
<script>
functionmyfunc()
{
var list = document.getElementsByTagName("ul")[0];
list.getElementsByTagName("li")[0].innerHTML = "Numbers";
}
</script>
</body>
</html>
E.g.2-
<html>
<head></head>
<body> After click on button
<table id="forecast-table">
<td>one </td>
<td>two </td>
<td>three </td>
</table>
<button onclick="myfunc()">Click To change table data</button>
<script>
functionmyfunc()
{
var list = document.getElementsByTagName("table")[0];
list.getElementsByTagName("td")[0].innerHTML = "Numbers";
}
</script>
</body>
</html>
E.g.3 -document.getElementsByClassName(name)
<body>
<div class="example">First div element with class="example".</div>
<div class="example">Second div element with class="example".</div>
<p>Click the button to change the text of the first div element with
class="example" (index 0).</p>
<button onclick="myFunction()">Try it</button>
<p><strong>Note:</strong> The getElementsByClassName() method is
not supported in Internet Explorer 8 and earlier versions.</p>
<script>
functionmyFunction() {
var x = document.getElementsByClassName("example");
x[0][1].innerHTML = "Hello World!";
}
</script>

</body>

=>after click
on
Try it
Button.

Change HTML Element –


Method Description
element.innerHTML =  new html Change the inner HTML of an
conten element
element.hasAttribute = new value The hasAttribute() method
returns true if the specified
attribute exists, otherwise it
returns false.
element.attribute = new value Change the attribute value of
an HTML element
element.setAttribute(attribute, value) Change the attribute value of
an HTML element
element.style.property = new style Change the style of an HTML
element

 E.g. 1–
element.innerHTML =  new html content
Change the inner HTML of an element
<body>
<p id="demo" onclick="myFunction()">Click me to change my HTML
content (innerHTML).</p>
<script>
functionmyFunction() {
document.getElementById("demo").innerHTML =
"Paragraph changed!";
}
</script>
</body>

After Click of text Click me

 E.g. 2 –
element.hasAttribute = new value
element.attribute = new value

note 1:
x=5
x += 2
x=7
x += 2
... is equivalent to ...

x=x+2

note 2:
It is the addition assignment operator (+=) adds a value to a variable.
For strings, you concat the current value with another value
var name ="User";

name+="Name";// name = "UserName";


For numbers, it will sum the value:
var n =3;

n +=2;// n = 5

<!DOCTYPE html>

<html>
<head>
<title>Attributes example</title>
<script type="text/javascript">
functionmyAttributeList() {
varmyparagraph = document.getElementById("paragraph");
varmyresult = document.getElementById("result");
// First, let's verify that the paragraph has some attributes
//element.hasAttribute = new value
//paragraph is id
if (paragraph.hasAttributes()) {
varmyattribute = paragraph.attributes;
var output = "";
for(vari = myattribute.length - 1; i>= 0; i--) {
output += myattribute[i].name + "->" + myattribute[i].value;
}
myresult.value = output;
}
else {
myresult.value = "No attributes to show";
}
}
</script>
</head>
<body>
<p id="paragraph" style="color: green;">Sample Paragraph</p>
<form action="">
<p>
<input type="button" value="Show first attribute name and value"
onclick="myAttributeList();">
<input id="result" type="text" value="">
</p>
</form>
</body>
</html>

Adding and Deleting Elements

Method Description
document.createElement(element) Create an HTML element
document.removeChild(element) Remove an HTML element
document.appendChild(element) Add an HTML element
document.replaceChild(element) Replace an HTML element
document.write(text) Write into the HTML output stream

Write example for each

Q. Explain
$(document).ready(function() {
})
Ans

JavaScript Basics

 Alert() and alert()


o Javascript is case sensitive
o Alert() is invalid

 Comment in js
o Single line - //
o Multi Line - /* .. */

 Datatype in js
o Number
o Boolean
o String

 Create variable in js
o Var keyword used to create any type of variable.
o E.g.
 var a = 10;
 var b = “MyString”;

 Javascript is a dynamic type language. It variable automatically


detect its data type.
 Concatenate in javascript
o E.g
PART 9 - CONVERTING STRINGS TO NUMBERS IN JAVASCRIPT

</html>
<head>
<title>convert string to num</title>

<script>
function addNumber()
{
var fnum =
document.getElementById("txtFirstNumber").value; //assign a value of
txtFirstNumber to var a
var snum =
document.getElementById("txtSecondNumber").value; //assign a value
of txtseconNumberNumber to var b
var result = fnum + snum;
document.getElementById("txtResult").value= result;
//assign a value to txtResult
} </script>
</head>
</body>
<table style="border:1px solid black; font-family:Arial">
<tr>
<td>First Number</td>
<td><input type="text" ID="txtFirstNumber"/></td>
</tr>
<tr>
<td>Second Number</td>
<td><input type="text"
ID="txtSecondNumber"/></td>
</tr>
<tr>
<td>Result</td>
<td><input type="text" ID="txtResult"/></td>
</tr>
<tr>
<td>
</td>
<td>
<input type="button" value="Add" id="btnAdd"
onclick="addNumber()"/>
</td>
</tr>
</table>
</body>
</html>

 Issue 1 – number are conncatenated


o is the output is incorrect. The program is concatenating two
number
o Solution – Use parseInt

var fnum =
parseInt(document.getElementById("txtFirstNumber").val
ue); //assign a value of txtFirstNumber to var a
var snum =
parseInt(document.getElementById("txtSecondNumber").v
alue); //assign a value of txtseconNumberNumber to var b

 Issue 2 – Decimal number are treated as Integer

o Solution – Use parseFloat


var fnum =
parseFloat(document.getElementById("txtFirstNumbe
r").value); //assign a value of txtFirstNumber to var a
var snum =
parseFloat(document.getElementById("txtSecondNum
ber").value); //assign a value of
txtseconNumberNumber to var b

 Issue 3 – NAN(not a number)


o We want to show some another error
o Solution – IsNan in if condition
function addNumber()
{
var fnum =
parseFloat(document.getElementById("txtFirstNumber").value
); //assign a value of txtFirstNumber to var a
var snum =
parseFloat(document.getElementById("txtSecondNumber").val
ue); //assign a value of txtseconNumberNumber to var b

if(IsNaN(fnum)){
alert("Enter first number");
}
if(IsNaN(snum)){
alert("Enter second number");
}
var result = fnum + snum;
document.getElementById("txtResult").value=
result; //assign a value to txtResult
}

 Issue 4 –
o We do not want to print NaN any way
o Solution – use return;
if(isNaN(fnum)){
alert("Enter first number");
return;
}
if(isNaN(snum)){
alert("Enter second number");
return;
}

 More better validation –


<script type="text/javascript">
function addNumber()
{
//first number
var fnum =
document.getElementById("txtFirstNumber").value;
if(fnum==""){
alert("Enter first number");
return;
}
fnum = parseFloat(fnum);
if(isNaN(fnum)){
alert("Enter valid first number");
return;
}

//Second number
var snum =
document.getElementById("txtSecondNumber").value;
if(snum==""){
alert("Enter Second number");
return;
}
snum = parseFloat(snum);
if(isNaN(snum)){
alert("Enter valid Second number");
return;
}

//result
var result = fnum + snum;
document.getElementById("txtResult").value=
result; //assign a value to txtResult
}
</script>

PART 10 - Strings in JavaScript Kudvenkat


And also
20 String Methods in 7 Minutes - Beau teaches JavaScript
Refer to
freeCodeCamp - https://www.youtube.com/watch?
v=VRz0nbax0uI
JavaScript Storage Interface sessionStorage localStorage Tutorial

https://www.youtube.com/watch?v=klLMeL7I4O0
 Create
o Here #login_user_name is an for a textbox.
o Assign value of #login_user_name to userid
o Store it in Jquery Session having username username
var userid = $('#login_user_name').val();
sessionStorage.setItem("username", userid);
 Use –
o Retrive session into a variable name user
var user = sessionStorage.username;

HOW TO CREATE AND USE SESSION IN JQUERY?

HOW TO SEND VIEW DATA TO CONTROLLER?


Ans .:
use ajax
HOW TO RETRIVE CONTROLLER VIEWBAG VALUE IN JQUERY?
Ans.:

Can i take value from Session(in controller) to TempData in view jquery.

Q. SQUARE ROOT IN JAVASCRIPT?


Ans.:
Math.sqrt(225);

O/P -25

You might also like