You are on page 1of 8

Unit 5 : JavaScript Functions

JavaScript Functions:

A JavaScript function is a block of code designed to perform a particular task. A JavaScript


function is executed when "something" invokes it (calls it). JavaScript functions
are defined with the function keyword, followed by a name, followed by parentheses ().

Function names can contain letters, digits, underscores, and dollar signs (same rules as
variables).

The parentheses may include parameter names separated by commas:


(parameter1, parameter2, ...)

The code to be executed, by the function, is placed inside curly brackets: {}

With functions you can reuse code

You can write code that can be used many times.

You can use the same code with different arguments, to produce different results.

Defining function (without parameters)


function function_name()
{
//code to be executed.
}

Defining function (with parameters)


function function_Name(parameters)
{
// code to be executed
}

calling function

Defining a function does not execute it. Defining it names the function and specifies what to do
when the function is called.

Calling the function actually performs the specified actions with the indicated parameters.

function_name() or function_name(parameters)

1
Unit 5 : JavaScript Functions

return statement

When JavaScript reaches a return statement, the function will stop executing.

If the function was invoked from a statement, JavaScript will "return" to execute the code after
the invoking statement.

Functions often compute a return value. The return value is "returned" back to the "caller":

function function_name()
{
//code to be executed.
return value;
}
Eg.
function myFunction(g1, g2) {
return g1 / g2;
}

Parameters are essentially passed to functions by value — so if the code within the body of a
function assigns a completely new value to a parameter that was passed to the function, the
change is not reflected globally or in the code which called that function.

When you pass an object as a parameter, if the function changes the object's properties, that
change is visible outside the function,

When you pass an array as a parameter, if the function changes any of the array's values, that
change is visible outside the function.

Passing objects as parameters.

function myFunc(theObject) {
theObject.make = "Toyota";
}
myFunc(theObject); //function call

passing array to function as parameters

function myFunc(theArr) {
theArr[0] = 30;
}

2
Unit 5 : JavaScript Functions

myFunc(arr); //call the function

Page Redirection
There may be a situation where you clicked a URL to reach a page X but internally you were
directed to another page Y. It happens due to page redirection. A redirect in JavaScript is a
technique that directs search engines and people to a different URL than the original. The
rerouted page may be located on the same or a different server. It might also take place on the
same or separate websites.

A web page can be redirected in a number of ways. The window.location object is used by
almost all functions. The most popular redirection techniques are location.href and
location.replace().

It may be used to obtain the current URL or web address's address. Without the window prefix,
the window.location object can be written.

One of the most often used is window.location objects. It's used to create a new document
from an existing one. We may give a new URL to this method, and it will initiate an HTTP
redirect in JavaScript. It differs from href in that it deletes the current document from the
document's history, making it impossible to return to the original.

Syntax

window.location.replace("new URL")

// Replaces the current document with a new one

or

window.location.href = "new URL";

// Sets or returns the entire URL

Alert Dialog box

An alert box is often used if you want to make sure information comes through to the user.

When an alert box pops up, the user will have to click "OK" to proceed.

alert("I am an alert box!");

3
Unit 5 : JavaScript Functions

Confirm Dialog box

A confirm box is often used if you want the user to verify or accept something.

When a confirm box pops up, the user will have to click either "OK" or "Cancel" to proceed.

If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box returns false.

var retVal = confirm("Do you want to continue ?");


if( retVal == true ) {
document.write ("User wants to continue!");
return true;
} else {
document.write ("User does not want to continue!");
return false;
}

Prompt dialog box

A prompt box is often used if you want the user to input a value before entering a page.

When a prompt box pops up, the user will have to click either "OK" or "Cancel" to proceed after
entering an input value.

If the user clicks "OK" the box returns the input value. If the user clicks "Cancel" the box returns
null.

var retVal = prompt("Enter your name : ", "your name here");


document.write("You have entered : " + retVal);

Form Validation
Basic form validation can be applied with 2 different ways.

Ex 1. For checking null values….

function validateform()
{
var name=document.myform.name.value;
var password=document.myform.password.value;

4
Unit 5 : JavaScript Functions

if (name==null || name=="")
{
alert("Name can't be blank");
return false;
}
else if(password.length<6)
{
alert("Password must be at least 6 characters long.");
return false;
}
}
</script>
<body>
<form name="myform" method="post" action="abc.html" onsubmit="return vali
dateform()" >
Name: <input type="text" name="name"><br/>
Password: <input type="password" name="password"><br/>
<input type="submit" value="register">
</form>

Ex 2 : For checking whether two passwords are same or not…

<script type="text/javascript">
function matchpass()
{
var firstpassword=document.f1.password.value;
var secondpassword=document.f1.password2.value;
if(firstpassword==secondpassword)
{
return true;
}
else{
alert("password must be same!");
return false;
}
}
</script>

<form name="f1" action="register.html" onsubmit="return matchpass()">


Password:<input type="password" name="password" /><br/>
Re-enter Password:<input type="password" name="password2"/><br/>
<input type="submit">
</form>

5
Unit 5 : JavaScript Functions

Ex 3 : For inputting only numbers in textbox…

<script>
function validate(){
var num=document.myform.num.value;
if (isNaN(num)){
document.getElementById("numloc").innerHTML="Enter Numeric value only";
return false;
}else{
return true;
}
}
</script>
<form name="myform" onsubmit="return validate()" >
Number: <input type="text" name="num"><span id="numloc"></span><br/>
<input type="submit" value="submit">
</form>

Using RegExp
A regular expression could be defined with the RegExp () constructor, as follows −
var pattern = new RegExp(pattern, attributes);
or
var pattern = /pattern/attributes;

Method associated with RegExp:


test() : Tests for a match in its string parameter.

Its syntax is as follows −


RegExpObject.test( string );

Returns the matched text if a match is found, and null if not.

Ex:
<html>
<head>
<title>JavaScript RegExp test Method</title>
</head>

6
Unit 5 : JavaScript Functions

<body>
<script type = "text/javascript">
var str = "Javascript is an interesting scripting language";
var re = new RegExp( "script", "g" );

var result = re.test(str);


document.write("Test 1 - returned value : " + result);

re = new RegExp( "pushing", "g" );

var result = re.test(str);


document.write("<br />Test 2 - returned value : " + result);
</script>
</body>
</html>

Character Description
[...] Any one character between the brackets.

[^…] Any one character not between the brackets.

[0-9] It matches any decimal digit from 0 through 9.

[a-z] It matches any character from lowercase a through lowercase z.

[A-Z] It matches any character from uppercase A through uppercase Z.

+ One or more character

* Zero or more character

? At most one character

{N} Matches N number of characters

{2,5} Character sequence of 2 to 5.

$ End with a character

^ Start with a character

7
Unit 5 : JavaScript Functions

\s Whitespace character

\S Non whitespace character

\d a digit (0-9)

\D a non-digit

\w a word character (a-z, A-Z, 0-9, _)

\W a non-word character

[aeiou] matches a single character in the given set

[^aeiou] matches a single character outside the given set

[java|script] matches any of the alternatives specified

function check()
{
var n=document.getElementById("txtname").value;
var pin=document.getElementById("txtpincode").value;
p=/\d+$/g;

if(n.match(p))
{
alert("Enter valid name");
return false;
}
else if(pin.length>8 || pin.length<8)
{
alert("Please enter 8 digits of pincode");
return false;
}
else
{
// return true;

}
}

You might also like