Category Archives: JavaScript

Miscellaneous scripts

Miscellaneous scripts

Javascript Add to favorite or book mark the link or url of the page

We store URL of sites by using my favorite or book mark feature. The URL of the site will be added to our favorite or bookmark links. We will use JavaScript function to do this. On clicking the link browser will open the window for conformation and adding the link to the list. Here is the function and below that the link to add the this site to your favorite list.

<SCRIPT LANGUAGE=”JavaScript“>
<!– Begin
function bookmark()
{
bookmarkurl=”http://www.plus2net.com”
bookmarktitle=”Plus2net.com: PHP SQL and Javascript Source”
if (document.all)
window.external.AddFavorite(bookmarkurl,bookmarktitle)
else if (window.sidebar) // firefox
window.sidebar.addPanel(bookmarktitle, bookmarkurl, “”);
}
// End –>
</script>

The above function should go the head section of the page and the link can be placed inside the body section of the page. Here is the code to place the link asking the visitors to click the link and add to their favorite.

<div align=”center”> <a href=”javascript:bookmark()”>Bookmark This Page</a> </div>

Image handling with javascript

Image handling

Background loading of image to cache by using JavaScript image object

While we are downloading any page we can also download images which are not going to be displayed immediately while showing the page. We can show the image by associating with an event and while displaying the content of the page the other image can be downloaded at background. This way the image will be downloaded to cache and then displayed from cache to the browser.

We will be using image object to download the image. One of its property src downloads the image. Here is the image object declaration and then downloading of image.

objImage = new Image();
objImage.src=”http://www.anyserver/image/2326.jpg”;

The above line will download the image to cache, we will try to connect displaying of this image with one event to see how fast the image loads. To do this we will have one simple function like this.

function displayimage(){
document.images['im'].src = ‘http://www.anyserver/image/2326.jpg”;
}

Once this function is called the image is displayed through a image tag (name = ) im. We will connect this function to one button onclick event like this.

<input type=”button” name=”Prev” value=” Show Image ” onClick=”displayimage()”>

To load the images while the page is loading we will use onload event of body tag. Here is the complete code. Replace the image urls of your choice. You will see the first image while page loads and allow some time for the remote image to load. Watch your status bar for messages and downloading of remote image file. Once you click the button the second image will display immediately with out any delay as it comes from the cache. If you are in a slow internet you can see the difference clearly. If you are in a fast net then try to connect to a heavy image to get the difference in speed. These concept will help us in building a JavaScript image slide show. Here is the complete code.

<html>
<head>
<title>(Type a title for your page here)</title>
<script language=”JavaScript”>

objImage = new Image();

function download(){
// preload the image file
objImage.src=”http://www.anyserver/image/2326.jpg”;
}

function displayimage(){
document.images[''im''].src = ”http://www.anyserver/image/2326.jpg”;
}

</script></head>

<body onLoad=”download()”>
<form name=”f1″>

<img name=”im” src=http://www.localserver/image/1263.jpg><br>
<input type=”button” name=”Prev” value=” Show Image ” onClick=”displayimage()”>
</form>
</body>
</html>

JavaScript Slideshow script using image object

We can create a slideshow by using client side JavaScript. Here for the slide show we will take a set of images and store them in an array. Inside the array only image address will be stored not the image. We will use image object to download and display the image. We will be downloading the next image while viewing any image in our slide show. Read the tutorial on how to download images at background to cache here.

In our script we will first create an array with urls of the images as array element. We will create an image object and inside the function download we will use this image object to download image at background to cache. This download function will be called once we successfully display an image from the array. Before that let us try to understand the buttons we will be using in our slide show.

We will be using two buttons to navigate in our slideshow. One button will move one step forward and other button will move one step backward. So each button will carry one value either +1 or -1 to tell what should be the next picture. The function name displaynext() receives these values and display the corresponding image. You can understand that at the last slide ( or image ) the NEXT button should be disabled as there is no next image . Same way at first slide the PREVIOUS button should be disabled. To work in all the browsers we will make it visible or hidden rather than making it enable or disable. Here is the code which will make NEXT button hidden at the last slide.

if(present_slide+1 >= images.length ){
document.f1.Next.style.visibility = “hidden”;
present_slide=images.length-1;
}else{document.f1.Next.style.visibility = “visible”;}

Same way at the first slide we will make previous button hidden.

if(present_slide+1 >= images.length ){
document.f1.Next.style.visibility = “hidden”;
present_slide=images.length-1;
}else{document.f1.Next.style.visibility = “visible”;}

Our main function displaynext(shift) will receive the value of shift based on the navigational buttons clicked ( it will either +1 or -1 ) and it will receive the value of 0 at the time of page load. Inside the function first the value of present slide is changed after adding the value of shift with present slide value. Then by one if condition the value of slide is checked as it should be within the values of image array. The value should be between 0 and number of element in the array. Once the if condition is satisfied, by using the .src property of the image element of the document the image is displayed. In the next line we will download the next image to be shown at background to cache. This way the next image can be shown immediately without any time delay. Here is the code of displaynext function.

function displaynext(shift){
present_slide=present_slide + shift;

if(images.length > present_slide && present_slide >= 0){
document.images[''im''].src = images[present_slide];

var next_slide=present_slide + 1;
download(next_slide); // Download the next image
}

At the time of page load we will pass a value of 0 to displaynext function to display the first element of the image array. While displaying this first element since the present slide value will be 0 so the previous button will not be visible. Here is the complete code of the slide show page.

<html>
<head>
<title>(Type a title for your page here)</title>
<script language=”JavaScript”>
var present_slide=0;

var images = new Array(”http://www.anyserver/image//2435.jpg”,
”http://www.anyserver/image//2436.jpg”,
”http://www.anyserver/image//2437.jpg”,
”http://www.anyserver/image//2438.jpg”,
”http://www.anyserver/image//2439.jpg”,
”http://www.anyserver/image//2440.jpg”,
”http://www.anyserver/image//2441.jpg”,
”http://www.anyserver/image//2442.jpg”);

objImage = new Image();
objImage = new Image();

function download(img_src){
// preload the image file
objImage.src=images[img_src];
}

function displaynext(shift){
present_slide=present_slide + shift;

if(images.length > present_slide && present_slide >= 0){
document.images[''im''].src = images[present_slide];

var next_slide=present_slide + 1;
download(next_slide); // Download the next image
}

if(present_slide+1 >= images.length ){
document.f1.Next.style.visibility = “hidden”;
present_slide=images.length-1;
}else{document.f1.Next.style.visibility = “visible”;}

if(present_slide<=0 ){
document.f1.Prev.style.visibility = “hidden”;
present_slide=0;
}else{
document.f1.Prev.style.visibility = “visible”;}
}
</script>
</head>
<body onLoad=”displaynext(0)”>

<form name=”f1″ method=post action=””>

<img name=”im” ></a><br>
<input type=”button” name=”Prev” value=” << ” onClick=”displaynext(-1);”>
<input type=”button” name=”Next” value=” >> ” onClick=”displaynext(1);”>
</form>
</body>
</html>

JavaScript Slideshow Rotator script

We can modify our JavaScript slide show script to show images automatically one after the other at a particular transition interval. Rotation is automatically triggered and user need to click the forward or backward buttons to navigate through the slideshow.

Please read JavaScript image slideshow script before adding this feature.

We will add one setTime function inside our displaynext function. This function will trigger the same displaynext function at an interval of 3 seconds. We can change this value and note that this function setTimeout accepts time duration values in milliseconds. You can read more on this at our JavaScript timer tutorials.

setTimeout(“displaynext(1)”, 3000);

Note that all other codes are same as Javascript Slideshow tutorial and you can remove the codes for navigational buttons if required after adding automatic transition to our slideshow. Here is the code of displaynext function with the setTimeout function added.

function displaynext(shift){
present_slide=present_slide + shift;

if(images.length > present_slide && present_slide >= 0){
//document.images[''im''].src = images[present_slide];
document.images[''im''].src = images[present_slide];

var next_slide=present_slide + 1;
download(next_slide); // Download the next image
setTimeout(“displaynext(1)”, 3000);
}

Javascript Strings Handling

Strings Handling

Converting Lower case text to Uppercase in JavaScript

We can convert lowercase letter to upper case letter by using toUpperCase() method in JavaScript. This you must have seen in some sites were after entering your user id and when we come out of input box, it changes to uppercase. Here this function toUpperCase() is used along with a event handler. Here is the basic syntax for toUpperCase method.

var a1 = str.toUpperCase();

Here str is our string variable. The new string ( with uppercase letters ) is stored in new variable a1.

Here is the sample code

var str=”This is my 1st new tutorial 123″;
var a1 = str.toUpperCase();
document.write(a1);

Converting Uppercase letters to Lower case in JavaScript

We have seen how to convert lower case letter to uppercase letter. Now we will learn how to convert upper case letters to lower case letters by using toLowerCase() functions in JavaScript. Here is the basic syntax for toLowerCase method.

var a2 = str.toLowerCase();

Here str is our string variable. The new string ( with lower case letters ) is stored in new variable a2.

Here is the sample code

var str=”This is my 1st new Tuorial 123″;
var a2 = str.toLowerCase();
document.write(a2);

Converting Uppercase letters to Lower case in JavaScript

We have seen how to convert lower case letter to uppercase letter. Now we will learn how to convert upper case letters to lower case letters by using toLowerCase() functions in JavaScript. Here is the basic syntax for toLowerCase method.

var a2 = str.toLowerCase();

Here str is our string variable. The new string ( with lower case letters ) is stored in new variable a2.

Here is the sample code

var str=”This is my 1st new Tuorial 123″;
var a2 = str.toLowerCase();

document.write(a2);

Math Function in Javascript

Math Function

Checking number using isNaN function

JavaScript has one important function isNaN() to check any data is number or string. This function isNaN() is remembered as short form is Is Not a Number. This function returns true if the data is string and returns false if the data is a number. Here is one simple example to check one string. We will use one if else condition check to display a message accordingly. Here is the code.

var my_string=”This is a string”;
if(isNaN(my_string)){
document.write (“this is not a number “);
}else{document.write (“this is a number “);
}

We will integrate this function to one JavaScript prompt. Here we will ask the user to enter a number. The value entered by user we will check by isNan function and display message accordingly. Here is the code.

var my_string = prompt(“Please enter a number”,”");
document.write(my_string)
if(isNaN(my_string)){
document.write (“this is not a number “);
}else{document.write (“this is a number “);

}

Javascript Date, Time & Timer related

Date, Time & Timer related

Timer funcitons in JavaScript: Reminder Script

Timers are used in web pages and we will discuss how to setup one and how to use one with an example. The function setTimeout() in function is used and here is its general syntax.

mytime = setTimeout(expression, msec);

mytime is the identifier used to identify the current timeout function.

expression is the statement that is to be executed after the specified time has ticked off.

msec is the duration of time in milliseconds after which the expression will be executed.

You can see by using setTimeout function we can execute any function or object after a set of time. For example if msec is set 5000 then the expression will be executed after 5 seconds or 5000 milliseconds.

We will try one example where we will have four period buttons and each button will set a different time for another function to execute and display a alert button. We will call it as a reminder script and we will get one alert box based on the period button we clicked. Note that we will be using onclick event of period button for this. Here is the demo and you will get alert message boxe based on the radio button you clicked.

Now here is the code to be used inside your head tags

<script type=”text/javascript”>
function remind(msg1) {
var msg = “This is a reminder after ” + msg1 +” Secs”;
alert(msg);
}
</script>

This is the code we used for displaying the period buttons

<input type=radio name=rm value=no checked>No reminder
<input type=radio name=rm value=5000 OnClick=”mytime=setTimeout(‘remind(2)’,2000)”>After 2 Secs
<input type=radio name=rm value=5000 OnClick=”mytime=setTimeout(‘remind(5)’,5000)”>After 5 Secs
<input type=radio name=rm value=5000 OnClick=”mytime=setTimeout(‘remind(10)’,10000)”>After 10 Secs

Resetting the timer funcitons in JavaScript

Here we will learn how to reset the timer function we have studied in part 1 of this tutorial. We can reset or clear the timer before the time out of the timer by using the function clearTimeout(). Here is the general syntax

clearTimeout(mytime)

mytime is the timer id we defined while activating the timer( please see the part 1 of this tutorial). It must be exactly same as one used in setTimeout function as it identify the timer with this.

setTimeout function sets the timer and executes it after the set time, before that if we want to cancel or reset the timer then we must use the clearTimeout function with timer id.

Now we will use the same domo ( in Timer Set of part 1 ) with the additional reset button for the timer. Here is the demo.

Now here is the code to be used inside your head tags

<script type=”text/javascript”>
function remind(msg1) {
var msg = “This is a reminder after ” + msg1 +” Secs”;
alert(msg);
}
</script>

This is the code we used for displaying the period buttons

<input type=radio name=rm value=no checked>No reminder
<input type=radio name=rm value=5000 OnClick=”mytime=setTimeout(‘remind(2)’,2000)”>After 2 Secs
<input type=radio name=rm value=5000 OnClick=”mytime=setTimeout(‘remind(5)’,5000)”>After 5 Secs
<input type=radio name=rm value=5000 OnClick=”mytime=setTimeout(‘remind(10)’,10000)”>After 10 Secs
<input type=button value=’Reset Timer’ OnClick=”clearTimeout(mytime)”>

Date object to display current date and time in alert window

We can display current date and time using JavaScript alert window by linking it to a button click event. We can place this button any where inside a page and display time and date once it is clicked by user. This is a simple script and we will try to develop better applications by learning such small examples.

We will be using built in Date object. We can create instances of this object and use in our script like this

var my_time = new Date()

Now this instance we can display by using JavaScript alert window.

alert(my_time);

Now this alert we will trigger when a button is clicked by a user. Here is onclick event of a button click.

<input type=button value=”Show Time” onclick=”show_now();”>

Here is the complete code for the page with Show Time button.

<html>
<head>
<title>(Type a title for your page here)</title>
<script type=”text/javascript”>
function show_now() {
var my_time = new Date();
alert(my_time);
}
</script>
</head>

<body bgcolor=”#ffffff” text=”#000000″ link=”#0000ff” vlink=”#800080″ alink=”#ff0000″>

<input type=button value=”Show Time” onclick=”show_now();”>

</body>
</html>

Getmonth function using date object

We can use Date object in JavaScript to collect the current month by using getMonth function. We will try to print the present month name by using this getMonth function. Note that getMonth function returns number of month from 0 to 11. That is, it will return 0 if the month is January and will return 1 if the month is February and so on. It will return 11 for the month December.

To display the month name in full, we will write one array with all the month names inside it. Then based on the value returned by getMonth function we will display the corresponding element from this month array.

<html>
<head>
<title>(Type a title for your page here)</title>
<script type=\”text/javascript\”>
function show_now(){
var my_month=new Date()
//var dt = new Date(\”Aug 16, 2005 05:55:00\”);
var month_name=new Array(12);
month_name[0]=”January”
month_name[1]=”February”
month_name[2]=”March”
month_name[3]=”April”
month_name[4]=”May”
month_name[5]=”June”
month_name[6]=”July”
month_name[7]=”August”
month_name[8]=”September”
month_name[9]=”October”
month_name[10]=”November”
month_name[11]=”December”

alert (“Current month = ” + month_name[my_month.getMonth()]);
}
</script></head>

<body bgcolor=”#ffffff” text=”#000000″ link=”#0000ff” vlink=”#800080″ alink=”#ff0000″>

<input type=button value=”Show Month” onclick=”show_now();”>

</body>
</html>

Javascript Window Child, Close, Refreshing

Window Child, Close, Refreshing

Displaying Alert window with message

We can display alert messages in a new window to the visitor using client side JavaScript alert function. This is one useful tool to inform or alert the user by displaying some messages. Alert message window will have only one button displaying “OK” and there is no conform or cancel button. To get the user input by displaying conform or cancel buttons we have to use confirm window function. Alerts can be programmed to display different messages based on requirements and it can be programmed by using server side scripting languages. But for showing alert window we have to use JavaScript commands only.

In our example we have shown one button and called a function show_alert by connecting it to onClick event of the button.

Here is the code to display an alert message window.

var msg = “Welcome to plus2net.com”;
alert(msg);

Here msg is the variable and we are displaying the text stored inside the variable msg in the alert box.
Here is the demo of this code. Click the button below to display the alert message.

Here is the code of the alert window

<html><head>
<title>(Type a title for your page here)</title>
<script type=”text/javascript”>
function show_alert() {
var msg = “Welcome to plus2net.com”;
alert(msg);
}
</script>
</head>

<body >

<input type=button value=’Click here to display alert message’ OnClick=”show_alert()”>

</body></html>

Displaying Alert window with message

By using JavaScript prompt we can ask the visitor to enter data to our system for further processing. The prompt command will display a window and ask visitor to enter some data. We can collect the data entered by the user and store them in a variable. Here is some example.
.
var my_string = prompt(“Please enter your name”);
document.write(my_string)

We can show some default text while displaying the prompt. Here is an example where a default message is displayed for the visitor to enter first name.

var my_string = prompt(“Please enter your name”,”enter your first name only”);
document.write(my_string
)

The above code will display the prompt window with some default text.

We can check the entered data by using if else condition.
Here is the demo of this code. Click the button below to display the prompt message.

Displaying Confirm window for user input

We can display a confirm box to the visitor and ask their opinion. This confirm window will have two buttons, one for OK and other for CANCEL. Visitor can click one if the two buttons and the user action can be captured by assigning this to a variable. The confirm box will return TRUE if the OK button is clicked and it will return FALSE if cancel button is clicked.

We can further improve this by linking the returned value of the confirm button to an alert window.

Here is the code for a confirm box linked to an alert window.

var my_string = confirm(“Are you satisfied with the quality of the tutorials here?”);
if(my_string){alert(“Thank you”);
}else{
alert(“Please use the contact us page to give your feedbacks”);}

Here is the demo of this code. Click the button below to display the confirm options .

Opening a small (or child ) window from a main ( or parent ) window

We can open a small window known as child window by clicking a button or a link or a image of a main window. We can control the width, height and location ( alignment from top left corner of the screen ) of the small window from the main window. Here we can control the status bar, tool bar and resize the child window from the main window. By changing the value of status to 1 form 0 (status=1;) we can display the status bar for the child window. Same way by making the toolbar=1; we can display the tool bars for the small window. We can change the value of left to position the window horizontally. If we make the value of left to 0 like left=0; to align the window to left edge of the screen. Same way by making the top=0; we can place the window at the top of the screen. Don’t forget to refresh the parent window every time you change the parameters.

Here is the code at the parent window to display the link. Click the demo link to see how the window opens.

Here is the code of the above link

<a href=”javascript:void(0);”
NAME=”My Window Name” title=” My title here ”
onClick=window.open(“window-child.html”,”Ratting”,”width=550,height=170,0,status=0,”);>Click here to open the child window</a>

Here is a button to open the same window

<input type=button onClick=window.open(“window-child.html”,”Ratting”,”width=550,
height=170,left=150,top=200,toolbar=0,status=0,”); value=”Open Window”>

Scrollbar on child window
We can add scroll bar to child window by adding scrollbars=1 while opening the window. Here is the modified code.

<a href=”javascript:void(0);”
NAME=”My Window Name” title=” My title here ”
onClick=window.open(“window-child.html”,”Ratting”,”width=550,height=170,0,status=0,scrollbars=1″);>Click here to open the child window</a>

Closing of a small (or child ) window On click of button

A child window can be closed after displaying some information or taking some inputs from the user. The window can be self closed or can be closed by clicking a button or a link inside it. To know on how to open a child or small window you can refer to our tutorial here. You can take the input from user and automatically close the window depending on the requirements. Even you can refresh the parent window while before closing the main window. Here are the commands for closing the child window.

<input type=button onClick=”self.close();” value=”Close this window”>

Refreshing parent window from child window

Refreshing the parent window or main window from a child or small window is a common requirement. For example in an auction script we can display the present highest bid and we can ask the bidder to enter the bid amount by opening a child window. Here once the bid is entered and submitted the child window should close and then the parent window must refresh to display the entered bid amount. Here we will use the code at the child window to refresh the parent window. Please read the child window open and child window close tutorials before trying this. Here is the code to refresh the parent window from the child window.

<input type=button onClick=window.open(“window-child2.html”,”Ratting”,”width=550,height=170,
left=150,top=200,toolbar=0,status=0,”); value=”Open Window”>

The code of the child window is here

<html>
<head>
<title>(Type a title for your page here)</title>

<SCRIPT language=JavaScript>
<!–
function win(){
window.opener.location.href=”window-refreshing.php”;
self.close();
//–>
}
</SCRIPT>

</head>
<body bgcolor=”#ffffff” >

<font face=’Verdana’ size=’2′ >This is the child window opened . Click the button below to close this window and refresh the main window</font>
<br><br>
<center><input type=button onClick=”win();” value=”Close this window”></center>

</body>
</html>

Event handling in JavaScript

Event handling in JavaScript

Managing Status bar message onMouseOver of a link

WE can use windows status bar to display messages by linking it with events. We will be using windows objects status property to display this message.

Status bar is at the bottom of your browser. If it is not visible then go to View menu of your browser and click the status bar option. One check or tick will appear before the status bar option and the bar at the bottom of your browser will be displayed.

We will use onMouseOver and onMouseOut events of a hyper link to display or manage the messages.

Here is the demo which is a hyper link pointing to home page of this site ( plus2net.com )

Now let us see the code of the above demo

<a href=”../” onMouseOver=”window.status=”Welcome to Pluse2net.com Home page”; return true” onMouseOut=”window.status=”Enjoy reading JavaScript tutorials ”; return true”>Visit Home page</a>

As you can see in the above example we can display any message in our status bar while the mouse is over the hyper link. By default the status bar shows the URL of the link if no event is written. This way visitor comes to know about the address of the link when they place their mouse over it. Using the above code example we can change the displayed URL to a different location while the hyper link takes you to another location. For example the link below is telling you that your are going to google.com and the status bar is going to show you the google page URL, but once you click the link it will take you to plus2net.com home page. Here is the demo

See the code below and watch how the OnMouseOver event is written to display a different URL than the actual one.

<a href=”http://www.plus2net.com” onMouseOver=”window.status=”http://www.google.com”; return true” onMouseOut=”window.status=’Enjoy reading JavaScript tutorials ‘; return true”>Visit Google</a>

Form & component validation (JavaScript)

Form & component validation

Javascript Form Validation

PHP Advance Form validation code

PHP form validation is a frequent requirement in many applications. Different type of php form validations is used based on the requirements but the process remains same. Let us start with a simple one and then go to the complex email validation using PHP regular expression.

Let us keep an input box and we will not allow any user to enter null data in it. So our form validation script will check for null entry and do the processing accordingly. Our main page where form is there is called form.php and let us posts the data to another page and name it as  form_validate.php. We will check and validate the variables in form_validate.php page. Here is the simple html form.

<form method=post action=form_validate.php>
<input type=text name=userid>
<input type=text name=password>
<input type=submit value=Submit></form>

On submit of this form all entered variables will be available on form_validate.php page so let us go to form_validate.php page and read the variable and check if any value is there or not. Let us use one flag to check the status of the variables for form validation.

<?php

$flag=”OK”;   // This is the flag and we set it to OK
$msg=”";        // Initializing the message to hold the error messages

if(strlen($userid) < 5){    // checking the length of the entered userid and it must be more than 5 character in length
$msg=$msg.”( Please enter user id more than 5 character length  )<BR>”;
$flag=”NOTOK”;   //setting the flag to error flag.
}

User id validation is over, now let us start password checking.

if(strlen($password) < 5 ){    // checking the length of the entered password and it must be more than 5 character in length
$msg=$msg.”( Please enter password of more than 5 character length  )<BR>”;
$flag=”NOTOK”;   //setting the flag to error flag.
}

Now let us check the flag and give message accordingly, if the flag is set to OK then all validations is passed and we can proceed for the database checking. If the flag is set to NOTOK then entries are not ok so we have to display the messages.  We also give one back button for the user to go back and correct the entries.

if($flag <>”OK”){
echo “<center>$msg <br>
<input type=’button’ value=’Retry’ onClick=’history.go(-1)’></center>”;
}else{ // all entries are correct and let us proceed with the database checking etc …
}

This is PHP form validation by using two simple text boxes. We have checked only the number of characters entered by the user. Now let us move one more step and go for form validation checking the type of entry. Say in userid field  other than   characters are not allowed. We will use same flag to set the status and append the message to the message variable.

if(ereg(‘[^A-Za-z]‘, $userid)){    //Only lower or upper case letters allowed.
$msg=$msg.”( Please use only alphabets a to z as userid   )<BR>”;
$flag=”NOTOK”;   //setting the flag to error flag.
}

Validation (checking ) of period button on submit of Form

Period buttons are used when the visitor has to select one of the many options available. For example in a signup form the visitor has to select the sex by clicking on Male or Female selection. In different cases there can be more than two options also. For example mode of payment can be any one of the options saying cash, check, draft, credit card, or wire transfer. We can select one of the options out of many choices. We can check or validate the submission by checking any selection is made or not. The form will not be submitted if no selection is made.

Please note that we will be using client side JavaScript validation so if the user browser has disabled JavaScript then we can’t detect the status of the selection by the user and the form will simply submit. For this reason many scripts use server side validations. In server side validation the data has to go and return from server so it takes time. JavaScript validation in client side is fast and we also can detect the JavaScript setting of the browser and redirect the visitor or give a warning message asking to enable JavaScript.

Validation (checking ) of checkbox selection on submit of Form

Check box is used to get user inputs within the form. A group of checkbox is used or a single check box is used to collect the options of the visitor. The difference in check box and period button is the user can’t select more than one option in case of period buttons. In checkbox the user can give more than one option. For example in a newsletter script you can ask the visitor to select their interested areas. Here the user can give one or more than one are as the area of interest. So all options are to be stored or covered for the user. This way we can get more than one option for a choice. Here we will try with one checkbox and in another tutorial we will consider more than one checkbox.

In signup forms you will see one checkbox asking you to read the term and condition of the site and the user must agree to this by selecting a checkbox. On submit of the form the status of this checkbox is checked and if not checked by the user then alert message is displayed saying the user has to agree to the terms and conditions.

The JavaScript code is kept within the head tag of the page. See the validation

<script type=”text/javascript”>
function validate(form) {
// Checking if at least one period button is selected. Or not.
if (!document.form1.sex[0].checked && !document.form1.sex[1].checked){

alert(“Please Select Sex”);
return false;}

if(!document.form1.agree.checked){alert(“Please Read the guidelines and check the box below”);
return false; }

return true;
}
</script>

To display the period button and check box see the code below.

<table border=’0′ width=’50%’ cellspacing=’0′ cellpadding=’0′ ><form name=form1 method=post action=action_page.php onsubmit=’return validate(this)’><input type=hidden name=todo value=post>

<tr bgcolor=’#ffffff’><td align=center ><font face=’verdana’ size=’2′><b>Sex</b><input type=radio name=sex value=’male’>Male </font><input type=radio name=sex value=’female’><font face=’verdana’ size=’2′>Female</font></td></tr>

<tr><td align=center bgcolor=’#f1f1f1′><font face=’verdana’ size=’2′><input type=checkbox name=agree value=’yes’>I agree to terms and conditions </td></tr>
<tr bgcolor=’#ffffff’><td align=center ><input type=submit value=Submit> <input type=reset value=Reset></td></tr>
</table></form>

Checkbox Array in a Form

Checkboxes can be used as arrays and the value can be collected using JavaScript. We will be discussing client side JavaScript and the collection of checkbox value. You can visit the php section for checkbox array handling using PHP server side scripting. We can create a group of checkbox by giving them the same name and that will create an array and from it we can collect the names of the check boxes for which it is checked.

Here are some commands we will be using to get the details of the events or actions we perform.

document.form1.scripts.length

This gives us the length of the array or the number of elements present in the array. If we know we are using 5 checkboxes then we can directly use the number 5 but it is a good to use this as this picks up all the checkboxes of the group without missing any thing. Note that the word scripts in the document.form1.scripts.length is the name of the array and same as the checkboxes name.

The JavaScript code is kept within the head tag of the page.

<script type=”text/javascript”>
function validate(form) {
// Checking if at least one period button is selected. Or not.
if (!document.form1.sex[0].checked && !document.form1.sex[1].checked){

alert(“Please Select Sex”); return false;}

var total=”"
for(var i=0; i < document.form1.scripts.length; i++){
if(document.form1.scripts[i].checked)
total +=document.form1.scripts[i].value + “\n”
}
if(total==”")
alert(“select scripts”) else
alert (total)

return false;
} </script>

To display the period button and checkboxes see the code below.

<table border=’0′ width=’50%’ cellspacing=’0′ cellpadding=’0′ ><form name=form1 method=post action=action_page.php onsubmit=’return validate(this)’><input type=hidden name=todo value=post>

<tr bgcolor=’#ffffff’><td align=center ><font face=’verdana’ size=’2′><b>Sex</b><input type=radio name=sex value=’male’>Male </font><input type=radio name=sex value=’female’><font face=’verdana’ size=’2′>Female</font></td></tr>

<tr><td align=center bgcolor=’#f1f1f1′><font face=’verdana’ size=’2′><b>Scripts You know</b><input type=checkbox name=scripts value=’JavaScript’>JavaScript <input type=checkbox name=scripts value=’PHP’>PHP <input type=checkbox name=scripts value=’HTML’>HTML </td></tr>

<tr bgcolor=’#ffffff’><td align=center ><input type=submit value=Submit> <input type=reset value=Reset></td></tr>

</table></form>

Check or Uncheck all in a group of checkbox in JavaScript

If we have a series or a group of check boxes then we can provide one button to check all the checkboxes at one go and another button to uncheck all the checked buttons by using client side JavaScript. This way the user in a single attempt can check or uncheck all the buttons. Note that this is a client side JavaScript feature so JavaScript execution is to be enabled in the client browser.

There are different ways to achieve this result; we can keep two buttons for this. One button will check all the checkboxes and other button will uncheck all the buttons. The same result we can achieve by using a single buttons also. We can also keep one checkbox to get the same functionality. When we check the single checkbox we can make all the checkboxes checked and by uncheck we can make all the checkboxes uncheck( Inside mailbox of hotmail.com you can see this ) . Let us start with two buttons first. One for check all and other for Uncheck all .

Here is the JavaScript function to be kept within the head tag

<SCRIPT LANGUAGE=”JavaScript”>
<!–

<!– Begin
function CheckAll(chk)
{
for (i = 0; i < chk.length; i++)
chk[i].checked = true ;
}

function UnCheckAll(chk)
{
for (i = 0; i < chk.length; i++)
chk[i].checked = false ;
}
// End –>
</script>

This is the HTML code to be kept inside the body tag.

<form name=”myform” action=”checkboxes.asp” method=”post”>
<b>Scripts for Web design and programming</b><br>
<input type=”checkbox” name=”check_list” value=”1″>ASP<br>
<input type=”checkbox” name=”check_list” value=”2″>PHP<br>
<input type=”checkbox” name=”check_list” value=”3″>JavaScript<br>
<input type=”checkbox” name=”check_list” value=”4″>HTML<br>
<input type=”checkbox” name=”check_list” value=”5″>MySQL<br>

<input type=”button” name=”Check_All” value=”Check All”
onClick=”CheckAll(document.myform.check_list)”>
<input type=”button” name=”Un_CheckAll” value=”Uncheck All”
onClick=”UnCheckAll(document.myform.check_list)”>

Here is the code for single button. Here is the single function we use inside our head tags.

<SCRIPT LANGUAGE=”JavaScript”>
<!–

<!– Begin
function Check(chk)
{
if(document.myform.Check_All.value==”Check All”){
for (i = 0; i < chk.length; i++)
chk[i].checked = true ;
document.myform.Check_All.value=”UnCheck All”;
}else{

for (i = 0; i < chk.length; i++)
chk[i].checked = false ;
document.myform.Check_All.value=”Check All”;
}
}

// End –>
</script>

Now the html part

<form name=”myform” action=”checkboxes.asp” method=”post”>
<b>Scripts for Web design and programming</b><br>
<input type=”checkbox” name=”check_list” value=”1″>ASP<br>
<input type=”checkbox” name=”check_list” value=”2″>PHP<br>
<input type=”checkbox” name=”check_list” value=”3″>JavaScript<br>
<input type=”checkbox” name=”check_list” value=”4″>HTML<br>
<input type=”checkbox” name=”check_list” value=”5″>MySQL<br>

<input type=”button” name=”Check_All” value=”Check All”
onClick=”Check(document.myform.check_list)”>

</form>

Here is the code for head part of the script

<SCRIPT LANGUAGE=”JavaScript”>
<!–

<!– Begin
function Check(chk)
{
if(document.myform.Check_ctr.checked==true){
for (i = 0; i < chk.length; i++)
chk[i].checked = true ;
}else{

for (i = 0; i < chk.length; i++)
chk[i].checked = false ;
}
}

// End –>
</script>

Here is the code for body part .

<form name=”myform” action=”checkboxes.asp” method=”post”>
<b>Scripts for Web design and programming</b><br>
<input type=”checkbox” name=”check_list” value=”1″>ASP<br>
<input type=”checkbox” name=”check_list” value=”2″>PHP<br>
<input type=”checkbox” name=”check_list” value=”3″>JavaScript<br>
<input type=”checkbox” name=”check_list” value=”4″>HTML<br>
<input type=”checkbox” name=”check_list” value=”5″>MySQL<br>

<input type=”checkbox” name=”Check_ctr” value=”yes”
onClick=”Check(document.myform.check_list)”><b>Check Control</b>

</form>

Enable and disable of text box through a checkbox

We may need to enable or disable a text box based on the input of the user by using disabled property of the element. For example we have some choices for the visitor and one of the options is Others. Once the visitor select the others options then ( only ) one text box will be enabled to allow the visitor to fill the details.

Here is the demo of this. Click the checkbox to enable or disable the text box.

We have used the body onload command to keep the text area disabled while the page is loading.

The full code is here.

<html>
<head>
<title>(Type a title for your page here)</title>
<script language=”JavaScript”>
<!–

function enable_text(status)
{
status=!status;
document.f1.other_text.disabled = status;
}
//–>
</script>
</head>
<body onload=enable_text(false);>

<form name=f1 method=post>
<input type=”checkbox” name=others onclick=”enable_text(this.checked)” >Others
<input type=text name=other_text>
</form>

</body>
</html>

Adding options to List Box in client side Javascript

Options to a drop down list box can be added dynamically using client side JavaScript. We will discuss a simple way of adding options to a list. The process of adding can be controlled based on different condition required. Depending on conditions options can be removed also.

Here we will take care that the options are added on the page load , so by default the list box is pre populated when the page is displayed. You can see the demo at the end of this page. The main function creates a new OPTION object and assigns values and text part of the option. Here is the function which collects the list box name, value and text as inputs and then adds the option to the list box. Here is the function

function addOption(selectbox,text,value )
{
var optn = document.createElement(“OPTION”);
optn.text = text;
optn.value = value;
selectbox.options.add(optn);
}


Note that each time the function is called, it adds a new option to the list box. So we can add one option by calling the function once. Like this.

addOption(document.drop_list.Month_list,”January”, “January”);

So this way we can create a drop down list box of all the months by calling the function each time for a month. So with this now you can easily create the list box. But we will add another step to this by using one array of months. So from the array of months we will loop through and add each month to the list box. Here is how to create the array

var month = new Array(“January”,”February”,”March”,”April”,”May”,”June”,
“July”,”August”,”September”,”October”,”November”,”December”);

So now once our array is ready with data, we will loop through the array by using for loop and then call the addOption function using the data of the array. Here is the code.

for (var i=0; i < month.length;++i){

addOption(document.drop_list.Month_list, month[i], month[i]);
}

You can see with this array we will able to populate the drop down list box of months. Here is the simple code for html body tag and the form with drop down list

<body bgcolor=”#ffffff” text=”#000000″ link=”#0000ff” vlink=”#800080″
alink=”#ff0000″ onLoad=”addOption_list()”;>

<FORM name=”drop_list” action=”yourpage.php” method=”POST” >

<SELECT NAME=”Month_list”>
<Option value=”" >Month list</option>
</SELECT>
</form>

</body>

Removing options from a List Box in client side Javascript

We can remove the options from a list box by using client side JavaScript. You can see the article explaining how to add options to a list box using JavaScript. Here we will discuss on how to remove option on selection and removing all the options in one go. We will use different functions and connect them to buttons to execute them. Here are some functions and there uses in removing the options. You can see the demo of this program here.

While the page loads we will try to populate the list box by using onload event of the body tag. The list box will be filled with data at the time of display to the visitors. The detail on how to add options to list box you can get here. So we will go to the next step

Removing all the options
To remove all the options from the list box we will loop through all the elements of the list box and remove one by one. We will use for loop to loop from 0 to selectbox.options.length-1. The total length ( or the number of elements ) of the array we can get by using selectbox.options.length and to this we are subtracting 1 as the first elements starts from 0 ( not from 1 ). Here is the function

function removeAllOptions(selectbox)
{
var i;
for(i=selectbox.options.length-1;i>=0;i–)
{
selectbox.remove(i);
}
}

The for loop will remove all the elements with the value of i changing from last element of the array to first element of the array.

Removing Selected Options
We can remove the options one by one or by selecting more than one option and then by pressing the button. Here also we will use the similar function like above but before deleting we will check if the option is checked or not. selectbox.options[i].selected will return true if the option is selected. This way we will check all the elements of the list box and if they are checked then we will add the command selectbox.options.remove(i); to remove that particular option from the list box. Here is the function.

function removeOptions(selectbox)
{
var i;
for(i=selectbox.options.length-1;i>=0;i–)
{
if(selectbox.options[i].selected)
selectbox.remove(i);
}
}

Adding the options
There is a full tutorial on adding the options to list box. So here is the function.

function addOption(selectbox,text,value )
{
var optn = document.createElement(“OPTION”);
optn.text = text;
optn.value = value;
selectbox.options.add(optn);
}

function addOption_list(selectbox){
addOption(document.drop_list.SubCat, “One”,”One”);
addOption(document.drop_list.SubCat, “Two”,”Two”);
addOption(document.drop_list.SubCat, “Three”,”Three”);
addOption(document.drop_list.SubCat, “Four”,”Four”);
addOption(document.drop_list.SubCat, “Five”,”Five”);
addOption(document.drop_list.SubCat, “Six”,”Six”);

}

Now we will see how the select box with the form and buttons are placed in the body are of the page. Each button is connected to one function with on click event handler. See here

<FORM name=”drop_list” action=”yourpage.php” method=”POST” >

<SELECT id=”SubCat” NAME=”SubCat” MULTIPLE size=6 width=10>
</SELECT><br>
<input type=button onClick=”removeOptions(SubCat)”; value=’Remove Selected’>
<input type=button onClick=”removeAllOptions(SubCat)”; value=’Remove All’>
<input type=button onClick=”addOption_list()”; value=’Add All’>

</form>

Transferring options from one multiple selection boxes to other

We can transfer options from one selection box to other by selecting one by one or at one go. The uses of such a type of selection are you can select more than one options and it offers a better picture than selecting a group of checkboxes. To get an idea how the script works, see the demo at the end of this page. You can download the page with this code also.

This tutorial explains on how to move elements from one list to other, there are one more tutorial where the second list options are dynamically added or generated based on the selection of the first list.

You can see there are four main functions the page does and each is connected to one button. All the buttons have onlick event handler connected to one function. The page on load calls one function adoption_all_list() through the body tag to populate the first drop down box with default values. There are tutorials on adding elements or options to a list box to know how the function works. There is another tutorial on removing options from the list box. You must read these two tutorials before reading this. So out of the four buttons we will discuss the button which moves the selected options from first list box to second list box. For other functions refer to those adding and removing option tutorials.

The function we will discuss is addOption_list(), it moves the selected options to the second list box. On execution of this function it collects the elements selected, to do this a for loop is used which loops through all the options of the first list box. The line

for(i=document.drop_list.Category.options.length-1;i>=0;i–)

does that. While inside the loop we can get the status of any element by checking selected event and it returns true if the element is selected. Then we can use if condition to get the status.

if(document.drop_list.Category[i].selected)
So if it is selected then we have to execute two steps ( inside the above if condition ) first we will add the option to second drop down list and then remove it from first list. Here are the two steps.

addOption(document.drop_list.SubCat, document.drop_list.Category[i].value, document.drop_list.Category[i].value);
removeOption(Category,i);

The first step uses addOption function to insert the option and the second step uses removeOption function to remove that element from fist list box.

Here is the full function code for moving elements from one drop down to second drop down.

function addOption_list(){
for(i=document.drop_list.Category.options.length-1;i>=0;i–) {
var Category=document.drop_list.Category;
if(document.drop_list.Category[i].selected){
addOption(document.drop_list.SubCat, document.drop_list.Category[i].value, document.drop_list.Category[i].value);
removeOption(Category,i);
}

}
}


Here is the html code to display the drop down boxes and the buttons.

<body onload=”addOption_all_list()” ;=”" alink=”#ff0000″ bgcolor=”#ffffff” link=”#0000ff” text=”#000000″ vlink=”#800080″>

<form name=”drop_list” action=”yourpage.php” method=”post”>
<input onclick=”addOption_all_list()” ;=”" value=”Add All” type=”button”>

<select name=”Category” multiple=”multiple” size=”7″>
<option value=”PHP”>PHP</option>
<option value=”ASP”>ASP</option>
<option value=”JavaScript”>JavaScript</option>
<option value=”HTML”>HTML</option><option value=”Perl”>Perl</option><option value=”MySQL”>MySQL</option></select>
<input onclick=”addOption_list()” ;=”" value=”Move >” type=”button”> <input onclick=”move_all_Option()” ;=”" value=”Move All >>” type=”button”> <select id=”SubCat” name=”SubCat” multiple=”multiple” size=”7″></select><input onclick=”removeAllOptions(SubCat)” ;=”" value=”Remove All” type=”button”>
</form>

Array In Javascript

ARRAY

How to create array and add element

We can create arrays in JavaScript in different ways. Handling of arrays using JavaScript is required in many applications. If we are processing a form then elements of the form can be managed as part of an array. We will learn some different points on use of arrays and before that we will learn some basics of JavaScript array.

How to create arrays in JavaScript?

We can declare an array like this

var scripts = new Array();

We can add elements to this array

scripts[0] = “PHP”;
scripts[1] = “ASP”;
scripts[2] = “JavaScript”;
scripts[3] = “HTML”;

Now our array scrips has 4 elements inside it and we can print or access them by using their index number. Note that index number starts from 0. To get the third element of the array we have to use the index number 2 . Here is the way to get the third element of an array.

document.write(scripts[2]);

We also can create an array like this

var no_array = new Array(21, 22, 23, 24, 25);

Displaying all elements of an array

We can display all elements of an array by looping through each element of the array. Here we will increment the index of the array by one in each loop and display elements of the array one by one. To identify how many loops we have to make we must know the total number of elements present inside the array. That we can find out like this

array_name.length

So this number we will set as upper limit of our number of rotation or looping. You can check our tutorial on creating array to create an array and now we will try to display each element of the array. Here is the code.

var scripts = new Array();
scripts[0] = “PHP”;
scripts[1] = “ASP”;
scripts[2] = “JavaScript”;
scripts[3] = “HTML”;

for (i=0;i<scripts.length;i++)
{
document.write(scripts[i] + “<br >”);
}

The for loop in the above code loops through the elements of the array and display one by one vertically by adding one line break at the end of each element. The upper limit of the for loop is set to script.length value which is in this case equal to 4

Introduction to Javascript

JavaScript is popular as a client side script in the web programing area. Java Script code gets execuated by a web browser. Here we will learn different types of codes in Java Script.

Enable JavaScript and detect disable setting of client browser

Are you using a browser that doesn’t support JavaScript?

If your browser does not support JavaScript, you can upgrade to a newer browser, such as Microsoft Internet explorer 6 or Netscape 6.

Have you disabled JavaScript?

If you have disabled JavaScript, you must re-enable JavaScript to use this page. To enable JavaScript:

Using Internet Explorer 6

  1. On the Tools menu, click Internet Options.
  2. Click the Security tab.
  3. Click Custom Level.
  4. Scroll to Scripting. Under Active scripting, click Enable.
  5. Click OK twice.

Using Netscape 6

  1. On the Edit menu, click Preferences.
  2. Click Advanced.
  3. Select the Enable JavaScript for Navigator check box.
  4. Click OK.

Redirecting Browser to a page if JavaScript support is not there

If you have developed a page which depends on JavaScript for form validation or for any other purposes then you would be interested in detecting the setting of the client browser and would like to redirect to a different page explaining how to enable or disable JavaScript. Here we will discuss how to check this setting and redirect to a different page accordingly. We can detect this by using noscript tag and if the JavaScript is disabled then the code within this noscript tag will be executed. Here is the code to do that. This code will detect if the script setting is disabled and will redirect to a page explaining how to enable or disable JavaScript with meta refresh in 2 seconds.

<noscript>

<meta http-equiv=”refresh” content=”2; URL=enable_javascript.php”>
<center>
<table cellpadding=”0″ cellspacing=”0″ border=”0″ width=”550″>
<tr><td width=”100%” valign=”top” class=”PPDesTxt”><b>Are you using a browser that doesn’t support JavaScript?</b></td></tr>

<tr><td width=”100%” valign=”top” class=”PPDesTxt”>If your browser does not support JavaScript, you can upgrade to a newer browser, such as <a href=”http://www.microsoft.com/windows/ie/downloads/ie6/default.asp”>Microsoft&reg; Internet Explorer 6</a> or <a href=”http://wp.netscape.com/computing/download/bdp/index.html”>Netscape 6</a>.</td></tr>

<tr><td width=”100%” valign=”top” class=”PPDesTxt”><b>Have you disabled JavaScript?</b></td></tr>

<tr><td width=”100%” valign=”top” class=”PPDesTxt”>If you have disabled JavaScript, you must re-enable JavaScript to use this page. To enable JavaScript:</td></tr>
</table>
<table cellpadding=”0″ cellspacing=”0″ border=”0″ width=”100%”>

<tr><td width=”100%” colspan=”2″><img src=”/images/T.gif” width=”1″ height=”25″ border=”0″></td></tr>
</table></td>
</tr><tr><td>

</noscript>

Detecting the browser used by the visitor

There are different types of browsers with different versions used by the visitor to access a website. For a server side program there is nothing to do or special care to be taken as the code remains in severs side. However for client side tags or scripts as they gets executed at visitor end they have to give equal output for different browsers used by visitors.

The main problem is all browsers are not equal and they behave differently for different scripts. Some of the differences are kept intentionally by the browsers. So at the developer end it became difficult to develop a common code. So we ( as developer ) have to find out the visitor browser details and accordingly execute the part of the code specially written for the browser. Now how to know what is the browser being used by the visitor?

The solution is navigator object

The navigator object used to detect different properties of the browser. All properties are again not supported by all the browser but by using some common properties we can identify the browser used. We will discuss about the properties of this navigator object and the outputs we will get for different browser.

Here are the navigator property values for your browser ( The code is below that )

UserAgent Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)
appName Microsoft Internet Explorer
appVersion 4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)
browserLanguage en-us
platform Win32

Here is the code which display above details about your browser

<table width=’100%’ border=’0′ cellspacing=’1′ cellpadding=’0′>

<script type=”text/javascript”>
var st;
st=”<tr><td><b>UserAgent </b></td><td>”+ navigator.userAgent + “</td></tr>”;
st=st + “<tr><td><b>appName </b></td><td>”+ navigator.appName + “</td></tr>”;
st=st + “<tr><td class=data><b>appVersion</b></td><td >”+ navigator.appVersion + “</td></tr>”;
st=st + “<tr><td class=data><b>browserLanguage</b></td><td >”+ navigator.browserLanguage + “</td></tr>”;
st=st + “<tr><td class=data><b>platform</b></td><td class=data>”+ navigator.platform + “</td></tr>”;

document.write(st);
</script>
</table>

Now let us write some code to identify the browser and develop the code specific to that.