[Go to site: main page, start]

0% found this document useful (0 votes)
3 views32 pages

JavaScript Codes

The document provides a comprehensive overview of JavaScript, covering topics such as changing HTML content, variable declaration, operators, objects, functions, conditional statements, loops, events, and error handling. It includes numerous code examples demonstrating how to implement various JavaScript features and functionalities within HTML. Additionally, it explains the use of dialog boxes and the Document Object Model (DOM) for interacting with web pages.

Uploaded by

likithamohinicb
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)
3 views32 pages

JavaScript Codes

The document provides a comprehensive overview of JavaScript, covering topics such as changing HTML content, variable declaration, operators, objects, functions, conditional statements, loops, events, and error handling. It includes numerous code examples demonstrating how to implement various JavaScript features and functionalities within HTML. Additionally, it explains the use of dialog boxes and the Document Object Model (DOM) for interacting with web pages.

Uploaded by

likithamohinicb
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

JavaScript

JavaScript Codes
Example to change HTML contents:
[Link]("demo").innerHTML = "Hello JavaScript";
Where to have javascript in HTML
Example of Script
<script>
[Link]("demo").innerHTML
= "My First JavaScript";
</script>

Example of function placed only inside <head>

<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
[Link]("demo").innerHTML = "Paragraph changed.";
}
</script>
</head>
<body>
<h2>Demo JavaScript in Head</h2>
<p id="demo">A Paragraph</p>
<button type="button" it</button>
</body>
</html>

1
JavaScript

Example of function places only inside <body>

<!DOCTYPE html>
<html>
<body>
<h2>Demo JavaScript in Body</h2>
<p id="demo">A Paragraph</p>
<button type="button" it</button>

<script>
function myFunction() {
[Link]("demo").innerHTML = "Paragraph changed.";
}
</script>
</body>
</html>
Example of Output display
Using innerHTML
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My First Paragraph</p>
<p id="demo"></p>

<script>
[Link]("demo").innerHTML = 5 + 6;
</script>
</body>
</html>

2
JavaScript

Using [Link]()

<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>

<script>
[Link](5 + 6);
</script>
</body>
</html>

Syntax of javascript examples:


// How to create variables:
var x;
let y;

// How to use variables:


x = 5;
y = 6;
let z = x + y;

Example of declaration of variables


Declared as var:
var x = 5;
var y = 6;
var z = x + y;

Declared as let:
let x = 5;
let y = 6;
let z = x + y;

3
JavaScript

Declared as const:
const price1 = 5;
const price2 = 6;
let total = price1 + price2;

Block scope examples

Declared as let:
{
let x = 2;
}
// x can NOT be used outside the block.

Declared as var:
{
var x = 2;
}
// x CAN be used anywhere

Operators
Examples:
❖​ Assigning
// Assign the value 5 to x
let x = 5;
// Assign the value 2 to y
let y = 2;
// Assign the value x + y to z:
let z = x + y;

❖​ Adding
let x = 5;
let y = 2;
let z = x + y;

4
JavaScript

❖​Multiplying
let x = 5;
let y = 2;
let z = x * y;
❖​Arithmetic Operators Example
let a = 3;
let x = (100 + 50) * a;
❖​Assignment operator
let x = 10;
x += 5;
Example:
let text1 = "What a very ";
text1 += "nice day";
The result of text1 will be: What a very nice day

Objects
Example :
In real life, a car is an object.

A car has properties like weight and color, and methods like start and stop:

All cars have the same properties, but the property values differ from car to car.

All cars have the same methods, but the methods are performed at different times.

➢​ This code assigns a simple value (Fiat) to a variable named car:

let car = "Fiat";


➢​ This code assigns many values (Fiat, 500, white) to a variable named car:

const car = {type:"Fiat", model:"500", color:"white"};

5
JavaScript

Object Definition
Example
const person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};

Spaces and line breaks are not important. An object definition can span multiple lines:

Example:

const person = {

firstName: "John",

lastName: "Doe",

age: 50,

eyeColor: "blue"

};
Object Methods
Example:
const person = {
firstName: "John",
lastName : "Doe",
id ​ : 5566,
fullName : function() {
return [Link] + " " + [Link];
}
};

6
JavaScript

JavaScript Functions
Example:
// Function to compute the product of p1 and p2
function myFunction(p1, p2)
{
return p1 * p2;
}
Function return
Example: Calculate the product of two numbers, and return the result:
let x = myFunction(4, 3); // Function is called, return value will end up in x
function myFunction(a, b)
{
return a * b; ​ // Function returns the product of a and b
}

The result in x will be:12

7
JavaScript

Conditional Statements
Example for if statement:
Make a "Good day" greeting if the hour is less than 18:00:
if (hour < 18)
{
greeting = "Good day";
}

The result of greeting will be: Good day

Example of else statement:

If the hour is less than 18, create a "Good day" greeting, otherwise "Good evening":

if (hour < 18) {


greeting = "Good day";
}
else {
greeting = "Good evening";
}

Example of else if statement:


If time is less than 10:00, create a "Good morning" greeting, if not, but time is less than
20:00, create a "Good day" greeting, otherwise a "Good evening":
if (time < 10) {
greeting = "Good morning";
} else if (time < 20) {
greeting = "Good day";
} else {
greeting = "Good evening";
}

8
JavaScript

Example of switch
This example uses the weekday number to calculate the weekday name:
switch (new Date().getDay())
{
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
break;
}

The result of day will be: Thursday

9
JavaScript

JavaScript Loops
The For Loop
Example:
for (let i = 0; i < 5; i++) {
text += "The number is " + i + "<br>";
}

From the example above:

Expression 1 sets a variable before the loop starts (let i = 0).

Expression 2 defines the condition for the loop to run (i must be less than 5).

Expression 3 increases a value (i++) each time the code block in the loop has been
executed.

➔​We can initiate many values in expression 1 (separated by comma):

Example:
for (let i = 0, len = [Link], text = ""; i < len; i++) {
text += cars[i] + "<br>";
}

➔​we can omit expression 1 (like when your values are set before the loop starts)

Example
let i = 2;
let len = [Link];
let text = "";
for (; i < len; i++)
{
text += cars[i] + "<br>";
}

10
JavaScript

➔​Expression 3 can also be omitted (like when you increment your values inside the
loop)
Example
let i = 0;
let len = [Link];
let text = "";
for (; i < len; )
{
text += cars[i] + "<br>";
i++;
}
The For In Loop
Syntax
for (key in object)
{
// code block to be executed
}

Example
const person = {fname:"John", lname:"Doe", age:25};
let text = "";
for (let x in person)
{
text += person[x];
}

11
JavaScript

The For Of Loop


Syntax
for (variable of iterable) {
// code block to be executed
}
Example:
const cars = ["BMW", "Volvo", "Mini"];
let text = "";
for (let x of cars) {
text += x;
}
The While Loop
Example:In the following example, the code in the loop will run, over and over again, as
long as a variable (i) is less than 10:
while (i < 10) {
text += "The number is " + i;
i++;
}
The Do While Loop
Syntax
do {
// code block to be executed
}
while (condition);
Example
do {
text += "The number is " + i;
i++;
}
while (i < 10);

12
JavaScript

JavaScript Break and Continue


The break statement can also be used to jump out of a loop:
Example
for (let i = 0; i < 10; i++)
{
if (i === 3) { break; }
text += "The number is " + i + "<br>";
}
The Continue Statement
Example: This example skips the value of 3:
for (let i = 0; i < 10; i++)
{
if (i === 3) { continue; }
text += "The number is " + i + "<br>";
}

JavaScript Labels
Syntax
break labelname;
continue labelname;
Example

const cars = ["BMW", "Volvo", "Saab", "Ford"];


list: {
text += cars[0] + "<br>";
text += cars[1] + "<br>";
break list;
text += cars[2] + "<br>";
text += cars[3] + "<br>";
}

13
JavaScript

JavaScript Events
HTML Events
HTML allows event handler attributes, with JavaScript code, to be added to HTML
elements.

With single quotes:

<element event='some JavaScript'>

With double quotes:

<element event="some JavaScript">

➢​In the following example, an onclick attribute (with code), is added to a <button>
element.
Example:
<button > = Date()">The time is?</button>

➢​In the following example the code changes the content of its own element (using
[Link])
Example:
<button = Date()">The time is?</button>

➢​JavaScript code is often several lines long. It is more common to see event
attributes calling functions:
Example:
<button time is?</button>

In the example above, the JavaScript code changes the content of the element with
id="demo".

14
JavaScript

Onclick Event Type


Example:
<html>
<head>
<script type = "text/javascript">
<!--
function sayHello()
{
alert("Hello World")
}
//-->
</script>
</head>

<body>
<p>Click the following button and see result</p>
<form>
<input type = "button" value = "Say Hello" />
</form>
</body>
</html>

15
JavaScript

Redirecting to webpage
There are a couple of ways to redirect to another webpage with JavaScript. The most
popular ones are [Link] and [Link]:
Example:
// Simulate a mouse click:
[Link] = "[Link]
OR
Example:
// Simulate an HTTP redirect:
[Link]("[Link]

Example 1
It is quite simple to do a page redirect using JavaScript at client side. To redirect your
site visitors to a new page, you just need to add a line in your head section as follows.
<html>
<head>
<script type = "text/javascript">
<!--
function Redirect() {
[Link] = "[Link]
}
//-->
</script>
</head>

<body>
<p>Click the following button, you will be redirected to home page.</p>

<form>
<input type = "button" value = "Redirect Me" />
</form>

</body>
</html>

16
JavaScript

JavaScript - Dialog Boxes

Alert Dialog Box

Example
<html>
<head>
<script type = "text/javascript">
<!--
function Warn() {
alert ("This is a warning message!");
[Link] ("This is a warning message!");
}
//-->
</script>
</head>

<body>
<p>Click the following button to see the result: </p>
<form>
<input type = "button" value = "Click Me" />
</form>
</body>
</html>

17
JavaScript

Confirmation Dialog Box


Example
<html>
<head>
<script type = "text/javascript">
<!--
function getConfirmation() {
var retVal = confirm("Do you want to continue ?");
if( retVal == true ) {
[Link] ("User wants to continue!");
return true;
} else {
[Link] ("User does not want to continue!");
return false;
}
}
//-->
</script>
</head>

<body>
<p>Click the following button to see the result: </p>
<form>
<input type = "button" value = "Click Me" />
</form>
</body>
</html>

18
JavaScript

Prompt Dialog Box


Example
The following example shows how to use a prompt dialog box −
<html>
<head>
<script type = "text/javascript">
<!--
function getValue() {
var retVal = prompt("Enter your name : ", "your name here");
[Link]("You have entered : " + retVal);
}
//-->
</script>
</head>

<body>
<p>Click the following button to see the result: </p>
<form>
<input type = "button" value = "Click Me" />
</form>
</body>
</html>

19
JavaScript

HTML DOM Documents


The document object is accessed with: [Link] or just document

Examples
let url = [Link];
Or
let url = [Link];

DOM compatibility

Example
if ([Link]) {
// If the W3C method exists, use it
} else if ([Link]) {
// If the all[] array exists, use it
}
else {
// Otherwise use the legacy DOM
}

JavaScript - Errors & Exceptions Handling

Syntax Errors:For example: the following line causes a syntax error because it is
missing a closing parenthesis.
<script type = "text/javascript">
<!--
[Link](;
//-->
</script>

20
JavaScript

Runtime Errors
For example, the following line causes a runtime error because here the syntax is
correct, but at runtime, it is trying to call a method that does not exist.
<script type = "text/javascript">
<!--
[Link]();
//-->
</script>

Logical Errors:Exception Handling

The try...catch...finally Statement

<script type = "text/javascript">


<!--
try {
// Code to run
[break;]
}

catch ( e ) {
// Code to run if an exception occurs
[break;]
}

[ finally {
// Code that is always executed regardless of
// an exception occurring
}]
//-->
</script>

21
JavaScript

Input Validation Example


This example examines input. If the value is wrong, an exception (err) is thrown.

The exception (err) is caught by the catch statement and a custom error message is
displayed:

<!DOCTYPE html>
<html>
<body>
<p>Please input a number between 5 and 10:</p>
<input id="demo" type="text">
<button type="button" Input</button>
<p id="p01"></p>

<script>
function myFunction() {
const message = [Link]("p01");
[Link] = "";
let x = [Link]("demo").value;
try {
if([Link]() == "") throw "empty";
if(isNaN(x)) throw "not a number";
x = Number(x);
if(x < 5) throw "too low";
if(x > 10) throw "too high";
}
catch(err) {
​ [Link] = "Input is " + err;
}
}
</script>

</body>
</html>

22
JavaScript

Examples
Here is an example where we are trying to call a non-existing function which in turn is
raising an exception. Let us see how it behaves without try...catch−

<html>
<head>
<script type = "text/javascript">
<!--
function myFunc() {
var a = 100;
alert("Value of variable a is : " + a );
}
//-->
</script>
</head>

<body>
<p>Click the following to see the result:</p>

<form>
<input type = "button" value = "Click Me" />
</form>
</body>
</html>

23
JavaScript

The finally Statement


Syntax
try {
Block of code to try
}
catch(err) {
Block of code to handle errors
}
finally {
Block of code to be executed regardless of the try / catch result
}

Example:
function myFunction() {
const message = [Link]("p01");
[Link] = "";
let x = [Link]("demo").value;

try {
if([Link]() == "") throw "is empty";
if(isNaN(x)) throw "is not a number";
x = Number(x);
if(x > 10) throw "is too high";
if(x < 5) throw "is too low";
}

catch(err) {
​ [Link] = "Error: " + err + ".";
}

finally {
[Link]("demo").value = "";
}
}

24
JavaScript

The throw Statement


Example: The following example demonstrates how to use a throw statement.
<html>
<head>
<script type = "text/javascript">
<!--
function myFunc() {
var a = 100;
var b = 0;

try {
if ( b == 0 ) {
throw( "Divide by zero error." );
} else {
var c = a / b;
}
}
catch ( e ) {
alert("Error: " + e );
}
}
//-->
</script>

</head>
<body>
<p>Click the following to see the result:</p>

<form>
<input type = "button" value = "Click Me" />
</form>

</body>
</html>

25
JavaScript

JavaScript - Form Validation


Example 1:
We will take an example to understand the process of validation. Here is a simple form in
html format.
<html>
<head>
<title>Form Validation</title>
<script type = "text/javascript">
<!--
// Form validation code will come here.
//-->
</script>
</head>

<body>
<form action = "/cgi-bin/[Link]" name = "myForm" onsubmit
= "return(validate());">
<table cellspacing = "2" cellpadding = "2" border = "1">

<tr>
<td align = "right">Name</td>
<td><input type = "text" name = "Name" /></td>
</tr>

<tr>
<td align = "right">EMail</td>
<td><input type = "text" name = "EMail" /></td>
</tr>

<tr>
<td align = "right">Zip Code</td>
<td><input type = "text" name = "Zip" /></td>
</tr>

26
JavaScript

<tr>
<td align = "right">Zip Code</td>
<td><input type = "text" name = "Zip" /></td>
</tr>

<tr>
<td align = "right">Country</td>
<td>
<select name = "Country">
<option value = "-1" selected>[choose yours]</option>
<option value = "1">USA</option>
<option value = "2">UK</option>
<option value = "3">INDIA</option>
</select>
</td>
</tr>

<tr>
<td align = "right"></td>
<td><input type = "submit" value = "Submit" /></td>
</tr>

</table>
</form>
</body>
</html>

27
JavaScript

Example 2:
If a form field (name) is empty, this function alerts a message, and returns false, to
prevent the form from being submitted:

function validateForm() {
let x = [Link]["myForm"]["fname"].value;
if (x == "") {
​ alert("Name must be filled out");
return false;
}
}
The function can be called when the form is submitted.

HTML Form Example


<form name="myForm" action="/action_page.php" > return validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>

Automatic HTML Form Validation

If a form field (fname) is empty, the required attribute prevents this form from being
submitted:

HTML Form Example


<form action="/action_page.php" method="post">
<input type="text" name="fname" required>
<input type="submit" value="Submit">
</form>

28
JavaScript

DB Connectivity
Create Connection

●​ Start by creating a connection to the database.


●​ Use the username and password from your MySQL database.

demo_db_connection.js:
var mysql = require('mysql');

var con = [Link]({


host: "localhost",
user: "yourusername",
password: "yourpassword"
});

[Link](function(err) {
if (err) throw err;
[Link]("Connected!");
});
●​ Save the code above in a file called "demo_db_connection.js" and run the file:
Run "demo_db_connection.js":
C:\Users\Your Name>node demo_db_connection.js

●​ Which will give you this result: Connected!

29
JavaScript

[Link] MySQL Create Database


Creating a Database
➔​To create a database in MySQL, use the "CREATE DATABASE" statement:

Example
➔​ Create a database named "mydb":
var mysql = require('mysql');
var con = [Link]({
host: "localhost",
user: "yourusername",
password: "yourpassword"
});

[Link](function(err) {
if (err) throw err;
[Link]("Connected!");
[Link]("CREATE DATABASE mydb", function (err, result)
{
if (err) throw err;
​ [Link]("Database created");
});
});
➔​Save the code above in a file called "demo_create_db.js" and run the file
Run "demo_create_db.js":
C:\Users\Your Name>node demo_create_db.js

➔​Which will give you this result: Connected !


Database created
Connected!
Database created

30
JavaScript

Thank you

31
JavaScript

32

You might also like