I. Basic of Javascript Q1. Introduction To JAVASCRIPT?
I. Basic of Javascript Q1. Introduction To JAVASCRIPT?
BASIC OF JAVASCRIPT
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;
<script language="javascript">
var num1;
var num2;
</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>.
<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"));
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;
</body>
</html>.
<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>
<html>
<body>
<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 –
The number is 0
The number is 1
The number is 2
CONTINUE –
E.G. 8 –
<html>
<body>
<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 –
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"};
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
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
If … Else -
o E.g.1–
<script>
num = Number(prompt("pick the number"));
if(!Number.isNaN(num))
{
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.
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 –
O/P -
O/P -
O/P –
12
E.G. 7 - arguments.length;
Return nos. of arguments
function myFunction(a, b) {
return arguments.length;
}
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 –
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
document.getElementById("demo").innerHTML =person.fullName();
</script>
</body>
</html>
O/P –
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();
<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
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.
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
<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
<button onclick="displayDate()">Try it</button>
o E.g.
<body>
<script>
function changeText(id) {
id.innerHTML = "Ooops!";
}
</script>
</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.
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 –
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
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.
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>
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";
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>
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
Q. Explain
$(document).ready(function() {
})
Ans
JavaScript Basics
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”;
</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>
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
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;
}
//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>
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;
O/P -25