Friday, August 31, 2012

Have You Learned JavaScript?


JavaScript Summary

This tutorial has taught you how to add JavaScript to your HTML pages, to make your web site more dynamic and interactive.

You have learned how to create responses to events, validate forms and how to make different scripts run in response to different scenarios.

You have also learned how to create and use objects, and how to use JavaScript's built-in objects.
For more information on JavaScript, please look at our JavaScript examples and our JavaScript reference.

Now You Know JavaScript, What's Next?

The next step is to learn about the HTML DOM, jQuery, and AJAX.
If you want to learn about server-side scripting, the next step is to learn ASP or PHP.

HTML DOM
The HTML DOM defines a standard way for accessing and manipulating HTML documents.
The HTML DOM is platform and language independent and can be used by any programming language like Java, JavaScript, and VBScript.

If you want to learn more about the DOM, please visit our HTML DOM tutorial.

jQuery
jQuery is a JavaScript Library.
jQuery greatly simplifies JavaScript programming.

If you want to learn more about jQuery, please visit our jQuery tutorial.

AJAX
AJAX = Asynchronous JavaScript and XML.
AJAX is not a new programming language, but a new way to use existing standards.
AJAX is about exchanging data with a server, and update parts of a web page - without reloading the whole page.

Examples of applications using AJAX: Google Maps, Gmail, Youtube, and Facebook tabs.
If you want to learn more about AJAX, please visit our AJAX tutorial.

ASP / PHP
While scripts in an HTML file are executed on the client (in the browser), scripts in an ASP/PHP file are executed on the server.

With ASP/PHP you can dynamically edit, change or add any content of a Web page, respond to data submitted from HTML forms, access any data or databases and return the results to a browser, customize a Web page to make it more useful for individual users.

Since ASP/PHP files are returned as plain HTML, they can be viewed in any browser.

If you want to learn more about ASP, please visit our ASP tutorial.
If you want to learn more about PHP, please visit our PHP tutorial.

JavaScript Create Your Own Objects


Objects are useful to organize information.

Try it Yourself - Examples


JavaScript Objects

Earlier in this tutorial we have seen that JavaScript has several built-in objects, like String, Date, Array, and more. In addition to these built-in objects, you can also create your own.

An object is just a special kind of data, with a collection of properties and methods.

Let's illustrate with an example: A person is an object. Properties are the values associated with the object. The persons' properties include name, height, weight, age, skin tone, eye color, etc. All persons have these properties, but the values of those properties will differ from person to person. Objects also have methods. Methods are the actions that can be performed on objects. The persons' methods could be eat(), sleep(), work(), play(), etc.

Properties

The syntax for accessing a property of an object is:

objName.propName

You can add properties to an object by simply giving it a value. Assume that the personObj already exists - you can give it properties named firstname, lastname, age, and eyecolor as follows:

personObj.firstname="John";
personObj.lastname="Doe";
personObj.age=30;
personObj.eyecolor="blue";

document.write(personObj.firstname);

The code above will generate the following output:
John

Methods

An object can also contain methods.

You can call a method with the following syntax:

objName.methodName()

Note: Parameters required for the method can be passed between the parentheses.
To call a method called sleep() for the personObj:
personObj.sleep();


Creating Your Own Objects

There are different ways to create a new object:

1. Create a direct instance of an object

The following code creates a new instance of an object, and adds four properties to it:

personObj=new Object();
personObj.firstname="John";
personObj.lastname="Doe";
personObj.age=50;
personObj.eyecolor="blue";
alternative syntax (using object literals):
personObj={firstname:"John",lastname:"Doe",age:50,eyecolor:"blue"};
Adding a method to the personObj is also simple. The following code adds a method called eat() to the personObj:
personObj.eat=eat;

2. Create an object constructor

Create a function that construct objects:

function person(firstname,lastname,age,eyecolor)
{
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;
}

Inside the function you need to assign things to this.propertyName. The reason for all the "this" stuff is that you're going to have more than one person at a time (which person you're dealing with must be clear). That's what "this" is: the instance of the object at hand.

Once you have the object constructor, you can create new instances of the object, like this:

var myFather=new person("John","Doe",50,"blue");
var myMother=new person("Sally","Rally",48,"green");
You can also add some methods to the person object. This is also done inside the function:
function person(firstname,lastname,age,eyecolor)
{
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;

this.newlastname=newlastname;
}

Note that methods are just functions attached to objects. Then we will have to write the newlastname() function:

function newlastname(new_lastname)
{
this.lastname=new_lastname;
}

The newlastname() function defines the person's new last name and assigns that to the person. 

JavaScript knows which person you're talking about by using "this.". So, now you can write: myMother.newlastname("Doe").

JavaScript Timing Events



With JavaScript, it is possible to execute some code at specified time-intervals. This is called timing events.

It's very easy to time events in JavaScript. The two key methods that are used are:
  • setInterval() - executes a function, over and over again, at specified time intervals
  • setTimeout() - executes a function, once, after waiting a specified number of milliseconds
Note: The setInterval() and setTimeout() are both methods of the HTML DOM Window object.

The setInterval() Method

The setInterval() method will wait a specified number of milliseconds, and then execute a specified function, and it will continue to execute the function, once at every given time-interval.

Syntax

setInterval("javascript function",milliseconds);

The first parameter of setInterval() should be a function.

The second parameter indicates the length of the time-intervals between each execution.

Note: There are 1000 milliseconds in one second.

Example

Alert "hello" every 3 seconds:
setInterval(function(){alert("Hello")},3000);

Try it yourself »

The example show you how the setInterval() method works, but it is not very likely that you want to alert a message every 3 seconds.

Below is an example that will display the current time. The setInterval() method is used to execute the function once every 1 second, just like a digital watch.

Example

Display the current time:
function myFunction()
{
setInterval(function(){myTimer()},1000);
}

function myTimer()
{
var d=new Date();
var t=d.toLocaleTimeString();
document.getElementById("demo").innerHTML=t;
}

Try it yourself »

How to Stop the Execution?

The clearInterval() method is used to stop further executions of the function specified in the setInterval() method.

Syntax

clearInterval(intervalVariable)

To be able to use the clearInterval() method, you must use a global variable when creating the interval method:

myVar=setInterval("javascript function",milliseconds);

Then you will be able to stop the execution by calling the clearInterval() method.

Example

Same example as above, but we have added a "Stop the timer" button:
var myVar;

function myFunction()
{
myVar=setInterval(function(){myTimer()},1000);
}

function myTimer()
{
var d=new Date();
var t=d.toLocaleTimeString();
document.getElementById("demo").innerHTML=t;
}

function myStopFunction()
{
clearInterval(myVar);
}

Try it yourself »

The setTimeout() Method

Syntax

setTimeout("javascript function",milliseconds);

The setTimeout() method will wait the specified number of milliseconds, and then execute the specified function.

The first parameter of setTimeout() should be a function.

The second parameter indicates how many milliseconds, from now, you want to execute the first parameter.

Example

Wait 3 seconds, then alert "Hello":
setTimeout(function(){alert("Hello")},3000);

Try it yourself »

How to Stop the Execution?

The clearTimeout() method is used to stop the execution of the function specified in the setTimeout() method.

Syntax

clearTimeout(timeoutVariable)

To be able to use the clearTimeout() method, you must use a global variable when creating the timeout method:

myVar=setTimeout("javascript function",milliseconds);

Then, if the function has not allready being executed, you will be able to stop the execution by calling the clearTimeout() method.

Example

Same example as above, but we have added a "Stop the alert" button:
var myVar;

function myFunction()
{
myVar=setTimeout(function(){alert("Hello")},3000);
}

function myStopFunction()
{
clearTimeout(myVar);
}

Try it yourself »

More Examples


Wednesday, August 29, 2012

JavaScript Form Validation


JavaScript Form Validation

JavaScript can be used to validate data in HTML forms before sending off the content to a server.
Form data that typically are checked by a JavaScript could be:
  • has the user left required fields empty?
  • has the user entered a valid e-mail address?
  • has the user entered a valid date?
  • has the user entered text in a numeric field?

Required Fields

The function below checks if a field has been left empty. If the field is blank, an alert box alerts a message, the function returns false, and the form will not be submitted:

function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
if (x==null || x=="")
  {
  alert("First name must be filled out");
  return false;
  }
}

The function above could be called when a form is submitted:

Example

<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
First name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>

Try it yourself »


E-mail Validation

The function below checks if the content has the general syntax of an email.

This means that the input data must contain an @ sign and at least one dot (.). Also, the @ must not be the first character of the email address, and the last dot must be present after the @ sign, and minimum 2 characters before the end:

function validateForm()
{
var x=document.forms["myForm"]["email"].value;
var atpos=x.indexOf("@");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
  {
  alert("Not a valid e-mail address");
  return false;
  }
}

The function above could be called when a form is submitted:

Example

<form name="myForm" action="demo_form.asp" onsubmit="return validateForm();" method="post">
Email: <input type="text" name="email">
<input type="submit" value="Submit">
</form>

Try it yourself »