9 Useful Javascripts - Offtopic Forum

Offtopic Forum

Banner 12


Notices

9 Useful Javascripts

This is a discussion on 9 Useful Javascripts within the Webmasters forums, part of the On Topics category; A Single click for checking-unchecking multiple check boxes You must have seen this script working at many places. One that ...

Reply
Old 07-07-2008, 08:27 PM   #1 (permalink)
Points: 31, Level: 1 Points: 31, Level: 1 Points: 31, Level: 1
Activity: 0% Activity: 0% Activity: 0%
 Tracker2's Avatar
 
Tracker2 has no status.
Status: Lurker
Join Date: Jul 2008
Posts: 7
Thanks: 0
Thanked 1 Time in 1 Post

Default 9 Useful Javascripts

A Single click for checking-unchecking multiple check boxes

You must have seen this script working at many places. One that comes to my mind is at Yahoo / Hotmail for checking or unchecking all the mails that are visible on the page. There are lots of places where you can use this script, generally when you want the user to carry out some task on either all or none of the items that you present to him.

Code:
<SCRIPT LANGUAGE = "JavaScript">
<!--
function modify_boxes(to_be_checked,total_boxes){
  	for ( i=0 ; i < total_boxes ; i++ ){
  	  	if (to_be_checked){
  	document.forms[0].chkboxarray[i].checked=true;
}
  	  	else{
  	  	
	document.forms[0].chkboxarray[i].checked=false;
  	  	}
  	} 	 
}
	  	 
-->
</SCRIPT>

<BODY>
<FORM>
<INPUT TYPE=checkbox NAME="chkboxarray" VALUE="1"><br>
<INPUT TYPE=checkbox NAME="chkboxarray" VALUE="2"><br>
<INPUT TYPE=checkbox NAME="chkboxarray" VALUE="3"><br>
<INPUT TYPE=button NAME="CheckAll" VALUE="Check All Boxes" onClick="modify_boxes(true,3)">
<INPUT TYPE=button NAME="UnCheckAll" VALUE="UnCheck All Boxes" onClick="modify_boxes(false,3)">
</FORM>
</BODY>
Note : The VALUE tag for the checkboxes seem to have no use. But it is required to differentiate between the check boxes when you submit such a form to a server side program. You could differentiate between the checked boxed by giving different VALUEs to the checkbox.


Opening a page (existing as well as dynamic) in a new window without bars, buttons, etc.

This script shows how to open a new page inside a new window rather than the existing window. You can also remove all the buttons and toolbars that exist in the standard browser window so that the entire new window is filled with only your content. You could either open an existing page or you could create dynamic content inside the new window.
Code:
<SCRIPT LANGUAGE = "JavaScript">
<!--

function open_new_window() {
  	dlg = window.open ("newpage.html" ,"NewWindowName" , "width=400,height=400,
toolbar=no,location=no,directories=no,
status=no,menubar=no,scrollbars=no,resizable=no")

}

function open_new_window2() {
  	dlg = window.open ("","NewWindowName2","width=400,height=400,toolbar=no,location=no,
directories=no,status=no,menubar=no,scrollbars=no,resizable=no")
dlg.document.write ("<BODY bgColor='#FFFFFF'>")
dlg.document.write ("<CENTER>This is text that has been added on the fly using Javascript.</CENTER>")
dlg.document.write ("</BODY>")

}
-->
</SCRIPT>

<BODY>
<A onClick='open_new_window()' >Click anywhere on this text to open the file newpage.html in a new window</a><br>

Or click on the button below to open a dynamically generated html page<br>

<FORM>
<INPUT type="button" value="New Window" onClick ='open_new_window2()' >
</FORM>
</BODY>

Multiple submit buttons on a single form (Submitting same form to any one of many programs)

This script shows you how to submit the contents of a form to different programs depending on which Submit button you press. Additionally it also shows how to call two different functions when you press the Submit button.

When you press submit on this script it first sets the variable totalboxes = 2, then it also sets the target for the form using the 3 if conditions stated. Then it calls the isReady() function and checks to see if atleast one checkbox has been checked. If even one is checked then it returns true and this causes the contents to be submitted to either program1.jsp or program2.jsp or program3.jsp. If even one checkbox wasn't checked you would be notified with a alert dialog box.
Code:
<SCRIPT LANGUAGE = "JavaScript">
<!--

var totalboxes;

function setCount(count, target){
  	

totalboxes=count;

// the next 3 lines are the main lines of this script
//remember to leave action field blank when defining the form
if(target == 0) document.myform.action="program1.jsp";
if(target == 1) document.myform.action="program2.jsp";
if(target == 2) document.myform.action="program3.jsp";

}

function isReady(form) {
  	for(var x=0 ; x<totalboxes ; x++){

	//if even one box is checked then return true
if(myform.boxes[x].checked) return true;
} 	 
  	

//default action : When even one was not checked then..
alert("Please check at least one checkbox..");
return false;

}

//-->
</SCRIPT>

<BODY>

<FORM onSubmit="return isReady(this)" METHOD="post" NAME="myform" ACTION="">
<INPUT TYPE="checkbox" NAME="boxes" VALUE="box1">Box 1 <BR>
<INPUT TYPE="checkbox" NAME="boxes" VALUE="box2">Box 2 <BR>
<INPUT TYPE="checkbox" NAME="boxes" VALUE="box2">Box 3 <BR>
<INPUT TYPE="checkbox" NAME="boxes" VALUE="box2">Box 4 <BR>
<INPUT TYPE="checkbox" NAME="boxes" VALUE="box2">Box 5 <BR>
</FORM>

<INPUT TYPE="image" onClick="setCount(5,0)" NAME="Submit1" VALUE="delete" SRC="delete_icon.jpg">
<INPUT TYPE="image" onClick="setCount(5,1)" NAME="Submit2" VALUE="view" SRC="view_icon.jpg">
<INPUT TYPE="image" onClick="setCount(5,2)" NAME="Submit3" VALUE="modify" SRC="modify_icon.jpg">

</BODY>
The setCount() take 2 parameters, the no of checkboxes and the target program to which the contents have to be submitted to.

Note : Sending the variable 5 for no of boxes using the onClick() event is useful in case you are not knowing the no. of checkboxes while writing the top part of the html page (while writing the script part at the top of the page). This may happen in case you are dynamically creating this html page then you may not know how many checkboxes would be present in the beginning. Basically this thing becomes useful since the dynamic languages such as ASP or JSP would generate the page line by line and at that time you would first generate the script part and then the actual checkboxes on the page. So you would not be able to set the value of totalboxes to a finite number before actually adding all the checkboxes to the page. You could use a counter (within ASP/JSP) which keeps track of the checkboxes you add to the html page and finally set the value of that counter as a parameter to this onClick() function.
You could avoid this by typing the Script at the bottom of the page, but that doesn't work with a few browsers. In case you haven't got the point, its ok.. Just understand how to submit the form to different programs. You can leave the checkbox part...

Emulating Browsers Back-Forward buttons
This is a simple script that many programmers know. Most of the users feel that this is a waste since the browsers Forward-Back buttons are already present. But you would realize that in case you are creating a window without the standard toolbars as shown in Example No.3 , then you would find this script to be very useful to emulate the Browsers buttons.

I have shown 2 ways.. I prefer the image one, since it looks really neat in case you have nice image.
Code:
<BODY>
<FORM>
<INPUT TYPE="image" SRC="N.jpg" NAME="back" onClick="window.history.go(-1)">
<INPUT TYPE="button" VALUE="Go Back" NAME="back" onClick="window.history.go(-1)">
<INPUT TYPE = "button" VALUE = "GO Forward" onClick = "window.history.go(1);">
</FORM>
</BODY>

Making the Output of a program (servlet/cgi program) to appear in a new frame
This script is used by most many programmers. I haven't found this script to be very helpful, since I try my best to avoid using frames on my website. Frames are to be avoided whenever, wherever possible. And I always manage without them.
Code:
<HTML>
<FRAMESET COLS="20%,*">
<FRAME SRC="leftindex.html" NAME="Left frame" >
<FRAME SRC="rightindex.html" NAME="Right frame">
</FRAMESET>
</HTML>
Below is the source of leftindex.html
Code:
<HTML>
<BODY>
<FORM NAME="Myform" METHOD=GET
ACTION="http://www.kiranpai.com/servlet1" onSubmit="document.myform.target = 'Right frame'>
<INPUT TYPE=SUBMIT VALUE="Clicking in left frame but Output in Right frame">
</FORM>
</BODY>
</HEAD>

Displaying a Countdown using Javascript
You require 5 images named countdown1.jpg, countdown2.jpg ..so on till countdown5.jpg each with repective digits on them, in the same directory as the script. When you load this page, after a delay of 2 seconds the images are displayed in the reverse order (from 5 down to 1) each after a delay of 1 second. This gives it a kewl effect of a countdown from 5 to 1 and then when it finishes a new blank window opens. The opening of a blank window was the simplest thing to use here. You can replace that with any other command.

I had used a slightly modified version of this countdown script during a press release of one of the websites I had developed. After the countdown the website opened in the new window. Ofcourse it was accompanied with claps and wows from the crowd present there :-) The effects looked wonderful since I had used 5 animated gifs, with each of them showing a sort of transformation (morphing) from one digit to another.

Code:
<SCRIPT LANGUAGE = "JavaScript">
<!--

x=5;
var pics= new Array();

for(i=1;i<=x;i++){
  	pics[i]=new Image();
pics[i].src="countdown"+i+".jpg";
}

function img(){
  	document.images[0].src=pics[x].src;
x--;
if(x>0) setTimeout('img()',1000);
if(x==0) setTimeout("msg=open('','DisplayWindow')",1000);

}
-->
</script>

<BODY onLoad="setTimeout('img()',2000)">
<B>The countdown from 5 to 1 will begin in 2 seconds</B>
</BODY>
Changing images with MouseOver and MouseOut events
This is probably the most common use of Javascript. There are countless ways to get this working, but I present one that I use frequently. This script like many of my other ones rely on numbered image files. Make images with names such as org0.jpg, org1.jpg and org2.jpg. These would be initially displayed. Get 3 more files named new1.jpg, new2.jpg and 3.jpg which would be the files displayed when the mouse is over the original images.
Code:
<SCRIPT LANGUAGE = "JavaScript">
<!--

function new_img(no){
  	document.images[no].src="new"+no+".jpg";
}

function org_img(no){
  	document.images[no].src="org"+no+".jpg";
}
-->
</SCRIPT>

<BODY>
<IMG SRC="org0.jpg" onMouseOver="new_img(0)" onMouseOut="org_img(0)">
<IMG SRC="org1.jpg" onMouseOver="new_img(1)" onMouseOut="org_img(1)">
<IMG SRC="org2.jpg" onMouseOver="new_img(2)" onMouseOut="org_img(2)">
</BODY>

Alternatively in case you want to change an image when clicked on it use the following script
<SCRIPT LANGUAGE = "JavaScript">
<!--

function change_img(index){
  	document.images[index].src = "N.jpg";

}
-->
</SCRIPT>

<BODY>
<A HREF="javascript: change_img(0)"><IMG SRC="I.jpg"></A>
</BODY>

Checking the form contents before submitting the form
This is once again an extremely important use of Javascript (this was one of the primary uses of Javascript). It reduces the time and resources on the server side for checking of online forms. Once again I have found many implementations of this script. This is one I find easy to understand.

Code:
<SCRIPT LANGUAGE = "JavaScript">
<!--
function isReady(recv_form) {
  	if (recv_form.feedback.value != "")
  	  	return true;
  	else {
  	  	alert("Please include a feedback message.");
recv_form.feedback.focus();
return false;
}
}
//-->
</SCRIPT>

<BODY>
<FORM NAME = "myform" onSubmit = "return isReady(this)" METHOD=POST ACTION = "http://www.kiranpai.com/servlet1">
<TEXTAREA NAME = "feedback"></TEXTAREA><br>
<INPUT TYPE="submit" VALUE="Submit">
</FORM>
</BODY>

Filling the values of a dropdown SelectMenu depending on the selection in another Menu


If you are developing a professional site for a company you would invariably come across a situation where you are expected to do the above. Remember that the power of this script becomes evident when you use Javascript along with some other dynamic language such as JSP or ASP. You could probably fill the arrays used in this script with some data fetched from a database relating to the particular user. When he selects an entry in the first dropdown menu, he is immediately presented with his relevant data in the second menu, instead of making another request to the server to fetch more data. These types of scripts are very useful when you have to allow a user select some thing from a general level to a more specific level. I mean each successive dropdown menu would be more and more specific choice. Read on to understand the entire thing.


Code:
<SCRIPT LANGUAGE = "JavaScript">
<!--

var tennisplayers= new Array("Safin", "Andre Agassi", "Pete Sampras", "Anna Kournikova", "Martina Hingis");
var cricketplayers = new Array("Sachin Tendulkar", "Steve Waugh", "Brian Lara", "Sir Don Bradman");

function set_player() {
  	

var select_sport = document.myform.sport;
var select_player = document.myform.player;
var selected_sport = select_sport.options[select_sport.selectedIndex].value;

select_player.options.length=0;
if (selected_sport == "tennis"){
  	  	for(var i=0; i<tennisplayers.length; i++)
  	  	select_player.options[select_player.options.length] = new Option(tennisplayers[i]);
  	}
if (selected_sport == "cricket"){
  	  	for(var i=0; i<cricketplayers.length; i++)
  	  	  	select_player.options[select_player.options.length] = new Option(cricketplayers[i]);
  	}

}
-->
</SCRIPT>

<BODY>
<FORM NAME="myform" METHOD="POST">

Sport
<SELECT NAME="sport" onChange="set_player()">
<OPTION VALUE="tennis">-------
<OPTION VALUE="tennis">Tennis
<OPTION VALUE="cricket">Cricket
</SELECT>

Player
<SELECT NAME="player">
<OPTION>------
</SELECT>

</FORM>
</BODY>
In the above script when the user selects either Cricket or Tennis in the first Select Menu, the choices in the second Select Menu automatically changes accordingly.
Tracker2 is offline   Reply With Quote
The Following User Says Thank You to Tracker2 For This Useful Post:
indian rep  (07-15-2008)
Old 07-15-2008, 07:55 PM   #2 (permalink)
Points: 1,001, Level: 17 Points: 1,001, Level: 17 Points: 1,001, Level: 17
Activity: 0% Activity: 0% Activity: 0%
 indian rep's Avatar
 
indian rep is feeling great
Status: Member
Join Date: Jun 2008
Posts: 397
Thanks: 5
Thanked 1 Time in 1 Post
My Mood:

Default

Quote:
Originally Posted by Tracker2 View Post



Opening a page (existing as well as dynamic) in a new window without bars, buttons, etc.

This script shows how to open a new page inside a new window rather than the existing window. You can also remove all the buttons and toolbars that exist in the standard browser window so that the entire new window is filled with only your content. You could either open an existing page or you could create dynamic content inside the new window.
Code:
<SCRIPT LANGUAGE = "JavaScript">
<!--

function open_new_window() {
  	dlg = window.open ("newpage.html" ,"NewWindowName" , "width=400,height=400,
toolbar=no,location=no,directories=no,
status=no,menubar=no,scrollbars=no,resizable=no")

}

function open_new_window2() {
  	dlg = window.open ("","NewWindowName2","width=400,height=400,toolbar=no,location=no,
directories=no,status=no,menubar=no,scrollbars=no,resizable=no")
dlg.document.write ("<BODY bgColor='#FFFFFF'>")
dlg.document.write ("<CENTER>This is text that has been added on the fly using Javascript.</CENTER>")
dlg.document.write ("</BODY>")

}
-->
</SCRIPT>

<BODY>
<A onClick='open_new_window()' >Click anywhere on this text to open the file newpage.html in a new window</a><br>

Or click on the button below to open a dynamically generated html page<br>

<FORM>
<INPUT type="button" value="New Window" onClick ='open_new_window2()' >
</FORM>
</BODY>
I already thanked to this post. But will this option would be available in even such browsers where popup blocker is permitted? Popup blocker is used in any browser and any user these days
__________________
I love to walk in rain. So that no one would find me crying.
indian rep is offline   Reply With Quote
Old 08-01-2008, 06:52 AM   #3 (permalink)
Points: 933, Level: 16 Points: 933, Level: 16 Points: 933, Level: 16
Activity: 0% Activity: 0% Activity: 0%
 ajcones's Avatar
 
ajcones has no status.
Status: Member
Join Date: Jul 2008
Posts: 195
Thanks: 0
Thanked 0 Times in 0 Posts

Send a message via Yahoo to ajcones
Default

That's a great collection of javascript codes. This can help if you are designing a new site especially if it is dynamic. There are also some codes that might help you at w3schools.com.
ajcones is offline   Reply With Quote
Reply

Bookmarks


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


Error. Page cannot be displayed. Please contact your service provider for more details. (18)


All times are GMT -6. The time now is 05:10 AM.
Powered by vBulletin® Version 3.7.3
Copyright ©2000 - 2017, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.2.0 RC7


Nav Item BG