To open a new window by using javascript we need to use window.open method. We can customize the window.open method as per the requirement.
Syntax:
window.open([URL], [Window Name], [Feature List], [Replace]);
Simple Example:
<a href="javascript:%20void(0)" onclick="window.open('popup.html', 'windowname1', 'width=200, height=77'); return false;">Click here for simple popup window</a>
This is a simple window.open method with minimum features included.
The features supported by the window.open method is:
Width --- Auto --- specifies width of the new window in pixels
height --- Auto --- height of the window in pixels
top --- Auto --- specifies window position
left --- Auto --- specifies window position
directories --- no--- should the directories bar be shown? (Links bar)
location --- no--- specifies the presence of the location bar
resizable --- no--- specifies whether the window can be resized.
menubar --- no--- specifies the presence of the menu bar
toolbar --- no--- specifies the presence of the toolbar
scrollbars --- no--- specifies the presence of the scrollbars
status --- no--- specifies the presence of the statusbar
Example when added the above features is:
<a href="javascript: void(0)"
onclick="window.open('popup.html',
'windowname2',
'width=200, \
height=77, \
directories=no, \
location=no, \
menubar=no, \
resizable=no, \
scrollbars=1, \
status=no, \
toolbar=no');
return false;">Click here for specific popup window</a>
Friday, September 25, 2009
Thursday, August 20, 2009
Check the Date
The below script provides to how to check the entered date is the correct date or not like by selecting the april if we select 31 days it has to prompt the entered date is the invalid date. Such type of scenarios can be tested with the below javascript.
var mth = new Array(' ','january','february','march','april','may','june','july','august','september','october','november','december');
var day = new Array(31,28,31,30,31,30,31,31,30,31,30,31);
function validateDate(fld,fmt,rng) {
var dd, mm, yy;var today = new Date;var t = new Date;fld = stripBlanks(fld);
if (fld == '') return false;var d1 = fld.split('\/');
if (d1.length != 3) d1 = fld.split(' ');
if (d1.length != 3) return false;
if (fmt == 'u' || fmt == 'U') {
dd = d1[1]; mm = d1[0]; yy = d1[2];
}
else if (fmt == 'j' || fmt == 'J') {
dd = d1[2]; mm = d1[1]; yy = d1[0];
}
else if (fmt == 'w' || fmt == 'W'){
dd = d1[0]; mm = d1[1]; yy = d1[2];
}
else return false;
var n = dd.lastIndexOf('st');
if (n > -1) dd = dd.substr(0,n);
n = dd.lastIndexOf('nd');
if (n > -1) dd = dd.substr(0,n);
n = dd.lastIndexOf('rd');
if (n > -1) dd = dd.substr(0,n);
n = dd.lastIndexOf('th');
if (n > -1) dd = dd.substr(0,n);
n = dd.lastIndexOf(',');
if (n > -1) dd = dd.substr(0,n);
n = mm.lastIndexOf(',');
if (n > -1) mm = mm.substr(0,n);
if (!isNumber(dd)) return false;
if (!isNumber(yy)) return false;
if (!isNumber(mm)) {
var nn = mm.toLowerCase();
for (var i=1; i < 13; i++) {
if (nn == mth[i] ||
nn == mth[i].substr(0,3)) {
mm = i; i = 13;
}
}
}
if (!isNumber(mm)) return false;
dd = parseFloat(dd); mm = parseFloat(mm); yy = parseFloat(yy);
if (yy < 100) yy += 2000;
if (yy < 1582 || yy > 4881) return false;
if (mm == 2 && (yy%400 == 0 || (yy%4 == 0 && yy%100 != 0))) day[mm-1]++;
if (mm < 1 || mm > 12) return false;
if (dd < 1 || dd > day[mm-1]) return false;
t.setDate(dd); t.setMonth(mm-1); t.setFullYear(yy);
if (rng == 'p' || rng == 'P') {
if (t > today) return false;
}
else if (rng == 'f' || rng == 'F') {
if (t < today) return false;
}
else if (rng != 'a' && rng != 'A') return false;
return true;
var mth = new Array(' ','january','february','march','april','may','june','july','august','september','october','november','december');
var day = new Array(31,28,31,30,31,30,31,31,30,31,30,31);
function validateDate(fld,fmt,rng) {
var dd, mm, yy;var today = new Date;var t = new Date;fld = stripBlanks(fld);
if (fld == '') return false;var d1 = fld.split('\/');
if (d1.length != 3) d1 = fld.split(' ');
if (d1.length != 3) return false;
if (fmt == 'u' || fmt == 'U') {
dd = d1[1]; mm = d1[0]; yy = d1[2];
}
else if (fmt == 'j' || fmt == 'J') {
dd = d1[2]; mm = d1[1]; yy = d1[0];
}
else if (fmt == 'w' || fmt == 'W'){
dd = d1[0]; mm = d1[1]; yy = d1[2];
}
else return false;
var n = dd.lastIndexOf('st');
if (n > -1) dd = dd.substr(0,n);
n = dd.lastIndexOf('nd');
if (n > -1) dd = dd.substr(0,n);
n = dd.lastIndexOf('rd');
if (n > -1) dd = dd.substr(0,n);
n = dd.lastIndexOf('th');
if (n > -1) dd = dd.substr(0,n);
n = dd.lastIndexOf(',');
if (n > -1) dd = dd.substr(0,n);
n = mm.lastIndexOf(',');
if (n > -1) mm = mm.substr(0,n);
if (!isNumber(dd)) return false;
if (!isNumber(yy)) return false;
if (!isNumber(mm)) {
var nn = mm.toLowerCase();
for (var i=1; i < 13; i++) {
if (nn == mth[i] ||
nn == mth[i].substr(0,3)) {
mm = i; i = 13;
}
}
}
if (!isNumber(mm)) return false;
dd = parseFloat(dd); mm = parseFloat(mm); yy = parseFloat(yy);
if (yy < 100) yy += 2000;
if (yy < 1582 || yy > 4881) return false;
if (mm == 2 && (yy%400 == 0 || (yy%4 == 0 && yy%100 != 0))) day[mm-1]++;
if (mm < 1 || mm > 12) return false;
if (dd < 1 || dd > day[mm-1]) return false;
t.setDate(dd); t.setMonth(mm-1); t.setFullYear(yy);
if (rng == 'p' || rng == 'P') {
if (t > today) return false;
}
else if (rng == 'f' || rng == 'F') {
if (t < today) return false;
}
else if (rng != 'a' && rng != 'A') return false;
return true;
Compare two dates
When working with the date of birth we need to check the date. We can check the date by writing the server side script. But when writing the server side script it takes so much time for the user which may not be usefull in some scenarios.
Below is the sample javascript method which compares the two date and proivdes the result whether the entered date is greater than the current date.
function comparedates()
{
var userdate=Date.parse("06/19/2008");
var currentdate=new Date;
if(userdate>Date.parse(currentdate))
{
alert("User Entered Date is greater then Current Date.");
}
else
{
alert("User Entered Date is less than the Current Date");
}
}
Below is the sample javascript method which compares the two date and proivdes the result whether the entered date is greater than the current date.
function comparedates()
{
var userdate=Date.parse("06/19/2008");
var currentdate=new Date;
if(userdate>Date.parse(currentdate))
{
alert("User Entered Date is greater then Current Date.");
}
else
{
alert("User Entered Date is less than the Current Date");
}
}
Monday, August 10, 2009
Validating the image
In the Forms the mostly common task we use is uploading the image. When uploading the image we are in need of certain condition like we need only images to be uploaded or only the documents files to be uploaded.
For such type of requirements we need to provide the javascript code for restricting the users from uploading. This script will be validated at the client side so there is not burden on the server side. Hence makes the server work more easier.
Below is the javascript code for checking the uploaded image is image format or not and intern check whether the uploaded image format is jpg,gif or png format.
function validate()
{
var extensions = new Array("jpg","jpeg","gif","png","bmp");
/*
// Alternative way to create the array
var extensions = new Array();
extensions[1] = "jpg";
extensions[0] = "jpeg";
extensions[2] = "gif";
extensions[3] = "png";
extensions[4] = "bmp";
*/
var image_file = document.form.image_file.value;
var image_length = document.form.image_file.value.length;
var pos = image_file.lastIndexOf('.') + 1;
var ext = image_file.substring(pos, image_length);
var final_ext = ext.toLowerCase();
for (i = 0; i < extensions.length; i++)
{
if(extensions[i] == final_ext)
{
return true;
}
}
alert("You must upload an image file with one of the following extensions: "+ extensions.join(', ') +".");
return false;
}
When ever you want to validate the file uploading control just copy this script and paste wherever you want to validate.If you want more formats you can add on the ext array.
The form is
<form name="form" action="http://test.com/test" enctype="multipart/form-data" method="post" onSubmit="return validate();">
<h2>Validate image on upload</h2>
Upload an image: <INPUT type="file" name="image_file"> <input type="submit" name="submit" value="Submit">
</form>
For such type of requirements we need to provide the javascript code for restricting the users from uploading. This script will be validated at the client side so there is not burden on the server side. Hence makes the server work more easier.
Below is the javascript code for checking the uploaded image is image format or not and intern check whether the uploaded image format is jpg,gif or png format.
function validate()
{
var extensions = new Array("jpg","jpeg","gif","png","bmp");
/*
// Alternative way to create the array
var extensions = new Array();
extensions[1] = "jpg";
extensions[0] = "jpeg";
extensions[2] = "gif";
extensions[3] = "png";
extensions[4] = "bmp";
*/
var image_file = document.form.image_file.value;
var image_length = document.form.image_file.value.length;
var pos = image_file.lastIndexOf('.') + 1;
var ext = image_file.substring(pos, image_length);
var final_ext = ext.toLowerCase();
for (i = 0; i < extensions.length; i++)
{
if(extensions[i] == final_ext)
{
return true;
}
}
alert("You must upload an image file with one of the following extensions: "+ extensions.join(', ') +".");
return false;
}
When ever you want to validate the file uploading control just copy this script and paste wherever you want to validate.If you want more formats you can add on the ext array.
The form is
<form name="form" action="http://test.com/test" enctype="multipart/form-data" method="post" onSubmit="return validate();">
<h2>Validate image on upload</h2>
Upload an image: <INPUT type="file" name="image_file"> <input type="submit" name="submit" value="Submit">
</form>
Saturday, June 6, 2009
Fixed Header and footer
I have gone through so many websites for the fixed header and footer and i found the below code as the best suitable for any type of browser.
IN the below downloaded code you will view only the CSS file which will make your work so easier. Everything is maintained in the CSS fiie. You need to just download the files and copy the selected CSS and use where ever you need to keep the header and the footer styles.
In this we have used the DIV tags to maintain the Header and the footer styles. The main advantage of this code is that it works best for all type of browsers(mozilla, internet explorer......)
IN the below downloaded code you will view only the CSS file which will make your work so easier. Everything is maintained in the CSS fiie. You need to just download the files and copy the selected CSS and use where ever you need to keep the header and the footer styles.
In this we have used the DIV tags to maintain the Header and the footer styles. The main advantage of this code is that it works best for all type of browsers(mozilla, internet explorer......)
Friday, May 22, 2009
Javascript Slideshow with timeout
We have so many sideshow available, The below also explains the same with some simple steps and with one java script method setTimeout).
This makes our work so simple to rotating the images.
<html>
<head>
<titleA Timed Slide Show</title>
<script type = "text/javascript">
var the_images = new Array();
the_images[0] = new Image();
the_images[0].src = "one.jpg";
the_images[1] = new Image();
the_images[1].src = "two.jpg";
the_images[2] = new Image();
the_images[2].src = "three.jpg";
var the_timeout;
function rotateImage(index)
{
window.document.my_image.src = the_images[index].src;
index++;
if (index >= the_images.length)
{
index = 0;
}
var the_function_string = "rotateImage(" + index + ");";
the_timeout = setTimeout(the_function_string, 1000);
}
Timing Events 165
</script>
</head>
<body>
<img name = "my_image" src = "one.jpg">
<form>
onClick = "clearTimeout(the_timeout);">
</form>
</body>
</html>
Code Explaination:
The first few lines set up the array containing the images we’ll put in the slide
show. Line creates the new array, sets the first item in the array equal to
an image object, and sets the src of that image object to the first picture of
the slide show. Lines and are just like the lines used to preload images
before an image swap. The next few
lines load the rest of the images.
After the images have loaded, and set up two variables for use in the
timing loop. Line declares the_timeout, which keeps track of each time-out,
and keeps track of which image in the slide show to bring up next time the
script calls rotateImage(). Keep in mind that declaring the index variable
outside the rotateImage() function, as I’ve done here in , is not the safest
programming practice—it’s just easier and quicker than the safe solution.
A safer version of rotateImage() will be described subsequently.
Next comes the rotateImage() function, which swaps in a new image and
then calls itself in one second. The first line of the function does the
image swap. It looks up the value of index, finds the src of the element numbered
index in the the_images array, and swaps in that image for my_image (the
image in).
After swapping the image, the function adds 1 to the index variable. The
next time rotateImage() gets called, it looks up the next item in the array and
swaps in that item. We have to make sure the number stored in index doesn’t
exceed the number of images stored in the the_images array. The if-then
statement starting in takes care of this issue by ensuring that if index has
incremented past the number of items in the array, it will be set back to 0
(corresponding to the first image in the the_images array). The last line in the
function should be old hat by now. This line sets a time-out to call the
rotateImage() function in one second.
Timing Events 163
The slide show starts when a visitor presses the button that calls
rotateImage() and ends when the user presses the Stop the Show button,
canceling the most recently set time-out.
This makes our work so simple to rotating the images.
<html>
<head>
<titleA Timed Slide Show</title>
<script type = "text/javascript">
var the_images = new Array();
the_images[0] = new Image();
the_images[0].src = "one.jpg";
the_images[1] = new Image();
the_images[1].src = "two.jpg";
the_images[2] = new Image();
the_images[2].src = "three.jpg";
var the_timeout;
function rotateImage(index)
{
window.document.my_image.src = the_images[index].src;
index++;
if (index >= the_images.length)
{
index = 0;
}
var the_function_string = "rotateImage(" + index + ");";
the_timeout = setTimeout(the_function_string, 1000);
}
Timing Events 165
</script>
</head>
<body>
<img name = "my_image" src = "one.jpg">
<form>
onClick = "clearTimeout(the_timeout);">
</form>
</body>
</html>
Code Explaination:
The first few lines set up the array containing the images we’ll put in the slide
show. Line creates the new array, sets the first item in the array equal to
an image object, and sets the src of that image object to the first picture of
the slide show. Lines and are just like the lines used to preload images
before an image swap. The next few
lines load the rest of the images.
After the images have loaded, and set up two variables for use in the
timing loop. Line declares the_timeout, which keeps track of each time-out,
and keeps track of which image in the slide show to bring up next time the
script calls rotateImage(). Keep in mind that declaring the index variable
outside the rotateImage() function, as I’ve done here in , is not the safest
programming practice—it’s just easier and quicker than the safe solution.
A safer version of rotateImage() will be described subsequently.
Next comes the rotateImage() function, which swaps in a new image and
then calls itself in one second. The first line of the function does the
image swap. It looks up the value of index, finds the src of the element numbered
index in the the_images array, and swaps in that image for my_image (the
image in).
After swapping the image, the function adds 1 to the index variable. The
next time rotateImage() gets called, it looks up the next item in the array and
swaps in that item. We have to make sure the number stored in index doesn’t
exceed the number of images stored in the the_images array. The if-then
statement starting in takes care of this issue by ensuring that if index has
incremented past the number of items in the array, it will be set back to 0
(corresponding to the first image in the the_images array). The last line in the
function should be old hat by now. This line sets a time-out to call the
rotateImage() function in one second.
Timing Events 163
The slide show starts when a visitor presses the button that calls
rotateImage() and ends when the user presses the Stop the Show button,
canceling the most recently set time-out.
Saturday, May 9, 2009
Show webpage content when scrolling comes
We may need to show some part of the page content. We will have the web pages with the page contents. When displaying the web pages there will be large content or small content. When we have the small content then the scrolling will not appear. So when we have the large content then we will have the scrolling option. So all the content will be scrolled from top to bottom.
But we need to only some part of the content need to be scrolled when the scrolling option is scrolled. The main content will not be scrolled when the page is scrolled.
Preview

Code
But we need to only some part of the content need to be scrolled when the scrolling option is scrolled. The main content will not be scrolled when the page is scrolled.
Preview
Code
Javascript disable right click
Disable right click option provides an option to disable the right click option when ever user wants to copy the content of the code. Disabling the right click also secures the data upto some part.
This is mainly used for the important data not to be disclosed to another persons or you dont want to provide an option to copy the images from your site to any another sites. Now a days this is the most common task to disable the right click functionality.
Javascript Code
<html>
<head>
<script language=JavaScript>
var message="This is the example to disable the right click";
///////////////////////////////////
function clickIE4(){
if (event.button==2){
alert(message);
return false;
}
}
function clickNS4(e){
if (document.layers||document.getElementById&&!document.all){
if (e.which==2||e.which==3){
alert(message);
return false;
}
}
}
if (document.layers){
document.captureEvents(Event.MOUSEDOWN);
document.onmousedown=clickNS4;
}
else if (document.all&&!document.getElementById){
document.onmousedown=clickIE4;
}
document.oncontextmenu=new Function("alert(message);return false")
// -->
</script>
</head>
<body>
This is the web page content ... You can place any content here................
</body>
</html>
This is mainly used for the important data not to be disclosed to another persons or you dont want to provide an option to copy the images from your site to any another sites. Now a days this is the most common task to disable the right click functionality.
Javascript Code
<html>
<head>
<script language=JavaScript>
var message="This is the example to disable the right click";
///////////////////////////////////
function clickIE4(){
if (event.button==2){
alert(message);
return false;
}
}
function clickNS4(e){
if (document.layers||document.getElementById&&!document.all){
if (e.which==2||e.which==3){
alert(message);
return false;
}
}
}
if (document.layers){
document.captureEvents(Event.MOUSEDOWN);
document.onmousedown=clickNS4;
}
else if (document.all&&!document.getElementById){
document.onmousedown=clickIE4;
}
document.oncontextmenu=new Function("alert(message);return false")
// -->
</script>
</head>
<body>
This is the web page content ... You can place any content here................
</body>
</html>
Thursday, April 30, 2009
Displaying Calender through javascript
Displaying the Calender is the most common script in all the websites. Now-a-days in every web application requiring the calender application. We have so many calender scripts found in the internet if we search, But i prefer this is the most user friendly calender script we can use. This was downloaded from cool dhtml website.
I have used this and found to be very useful and very flexible. IN the provided example we are given with all the possible options like displaying only the date or displaying the date and time option, By clicking single click the calender script will be pop up and we can select the appropriate date.
All the events are clearly mentioned. We can directly paste the code in our application and can use the following code.In this script we are provided with the draggable option.
Preview

I have used this and found to be very useful and very flexible. IN the provided example we are given with all the possible options like displaying only the date or displaying the date and time option, By clicking single click the calender script will be pop up and we can select the appropriate date.
All the events are clearly mentioned. We can directly paste the code in our application and can use the following code.In this script we are provided with the draggable option.
Preview

Monday, April 20, 2009
Reserved Key words and Triggering scripts with events
Javascript has some strict rules and referring to vairables. Your function name and variable name must begin with a letter and they can contain only letters, number and underscores. By conversion function and variables names must begin with lower letters, but they use uppercase for additional words. For example autotext() is completly different from autoText() in the javascript. Javascript is case sensitive.
Reserved Keywords:
abstract , boolean , byte , case , catch , char , class , const , debugger , default
delete , do , double , else , enum , export , extends , false , final , finally , float , for , function , goto , if , imports , in , int , interface , null , new , package
public , protected , return , this , throw , throws , typeof , true , try , void
Triggering scripts with events
autoText The scripts loads when a page is loaded. Like this we can call scripts when the user clicks the button or mouse overs on a image. Each of these clicks are called as events.
Some events are used by the document's BODY as a whole, and some are used by specific tags such as images , anchor tags , buttons.
Events that are assigned to the BODY Tag
1. onLoad when the document loads.
2. onUnload When a new document is loaded.
3. onFocus When the browser window recieves focus.
4. onBlur When the browser window loses focus.
5. onHelp when the user presses F1(IE only).
6. onKeypress when the user presses a key. Except the function keys.
Events that are used to tags includes
1.onFocus When the tag receives focus.
2.onBlur When the tag loses the focus.
3. onMouseOver When the user moves the mouse over the tag.
4. onMouseOut When the use moves the mouse away from the tag.
5. onChange When a form element value is changed.
6. onClick When a tag is clicked.
7. onSubmit When a form is submitted.
we can use these events to run our scripts based on different user actions
Reserved Keywords:
abstract , boolean , byte , case , catch , char , class , const , debugger , default
delete , do , double , else , enum , export , extends , false , final , finally , float , for , function , goto , if , imports , in , int , interface , null , new , package
public , protected , return , this , throw , throws , typeof , true , try , void
Triggering scripts with events
autoText The scripts loads when a page is loaded. Like this we can call scripts when the user clicks the button or mouse overs on a image. Each of these clicks are called as events.
Some events are used by the document's BODY as a whole, and some are used by specific tags such as images , anchor tags , buttons.
Events that are assigned to the BODY Tag
1. onLoad when the document loads.
2. onUnload When a new document is loaded.
3. onFocus When the browser window recieves focus.
4. onBlur When the browser window loses focus.
5. onHelp when the user presses F1(IE only).
6. onKeypress when the user presses a key. Except the function keys.
Events that are used to tags includes
1.onFocus When the tag receives focus.
2.onBlur When the tag loses the focus.
3. onMouseOver When the user moves the mouse over the tag.
4. onMouseOut When the use moves the mouse away from the tag.
5. onChange When a form element value is changed.
6. onClick When a tag is clicked.
7. onSubmit When a form is submitted.
we can use these events to run our scripts based on different user actions
Sunday, April 19, 2009
Checkbox array Enable / Disable
There will be two types of checkboxes one is the general checkbox and the second is the checkbox array. There will be a scenario that we need to read the value from the checkbox or the checkbox array.
Writing a javascript for the general checkbox is more easy when compared to the checkbox array. We need to write the javascript for checkbox array For example : We have a music options available and we need to provide option to enable the disable the checkbox array.
The below code explains how to enable and disable the checkbox array.
<Html>
<head>
//Music skills
function musicskills(value)
{
if(value==1)
{
chkvaluer=document.form.elements['chkmusic[]'];
for (r=0;r<chkvaluer.length;r++)
{
chkvaluer[r].disabled = true;
}
document.form.txtmusic.disabled = true;
}else{
chkvaluer=document.form.elements['chkmusic[]'];
for (r=0;r<chkvaluer.length;r++)
{
chkvaluer[r].disabled = false;
}
document.form.txtmusic.disabled = false;
}
}
</head>
<body>
<form name="form" method="post" action="testfile.php">
<input type="radio" value="yes" onClick="musicskills(0);">Yes
<input type="radio" value="no" onClick="musicskills(1);">No
<input type="checkbox" name="chkmusic[]" value="Punjabi">Punjabi
<input type="checkbox" name="chkmusic[]" value="classical">Classical
<input type="checkbox" name="chkmusic[]" value="devotional">Devotional
<input type="checkbox" name="chkmusic[]" value="westren">Westren
</body>
</html>
Writing a javascript for the general checkbox is more easy when compared to the checkbox array. We need to write the javascript for checkbox array For example : We have a music options available and we need to provide option to enable the disable the checkbox array.
The below code explains how to enable and disable the checkbox array.
<Html>
<head>
//Music skills
function musicskills(value)
{
if(value==1)
{
chkvaluer=document.form.elements['chkmusic[]'];
for (r=0;r<chkvaluer.length;r++)
{
chkvaluer[r].disabled = true;
}
document.form.txtmusic.disabled = true;
}else{
chkvaluer=document.form.elements['chkmusic[]'];
for (r=0;r<chkvaluer.length;r++)
{
chkvaluer[r].disabled = false;
}
document.form.txtmusic.disabled = false;
}
}
</head>
<body>
<form name="form" method="post" action="testfile.php">
<input type="radio" value="yes" onClick="musicskills(0);">Yes
<input type="radio" value="no" onClick="musicskills(1);">No
<input type="checkbox" name="chkmusic[]" value="Punjabi">Punjabi
<input type="checkbox" name="chkmusic[]" value="classical">Classical
<input type="checkbox" name="chkmusic[]" value="devotional">Devotional
<input type="checkbox" name="chkmusic[]" value="westren">Westren
</body>
</html>
Thursday, April 16, 2009
Checkbox read only
The below code will explain how can we make the checkbox enable and disable. Here we use the function deDemo() to enable / disable the checkbox and return the value of the checkbox is enabled.
<html>
<head>
<script type="text/javascript">
function doDemo(form) {
var cbObj = form.cbObj;
if (cbObj.checked)
alert("Value is " + cbObj.value);
else
alert("No value will be submitted.");
if (cbObj.disabled)
cbObj.disabled = false;
else
cbObj.disabled = true;
}
</script>
</head>
<body>
<center>
<b>Read-only Checkbox Demo</b>
<form>
<input type="checkbox" name="cbObj" value="Y" disabled>
<p>
<input type="button" value="Execute" onClick="doDemo(this.form)">
</form>
<hr>
</center>
</body>
</html>
<html>
<head>
<script type="text/javascript">
function doDemo(form) {
var cbObj = form.cbObj;
if (cbObj.checked)
alert("Value is " + cbObj.value);
else
alert("No value will be submitted.");
if (cbObj.disabled)
cbObj.disabled = false;
else
cbObj.disabled = true;
}
</script>
</head>
<body>
<center>
<b>Read-only Checkbox Demo</b>
<form>
<input type="checkbox" name="cbObj" value="Y" disabled>
<p>
<input type="button" value="Execute" onClick="doDemo(this.form)">
</form>
<hr>
</center>
</body>
</html>
Saturday, April 11, 2009
Checkbox array select / unselect
Generally in the checkbox, we have two different type of checkboxes one are plain checkboxes and the second one are checkbox array. The javascript for both differs a lot. The default checkbox script will be very simple to write and can be found any where in the net. The checkbox array scripts would be difficult.
The below example would define how to write a javascript for a checkbox array.
<html>
<head>
<script language="javascript">
function checkarray(form) {
var total = 0;
var max = document.form.elements['gender[]'].length;
for (var idx = 0; idx<max; idx++) {
if(document.form.elements['gender[]'][idx].checked==true)
{
if(document.form.elements['gender[]'][idx].value=="any")
{
for (var idx1 = 0; idx1<max; idx1++) {
document.form.elements['gender[]'][idx1].checked=true;
}
}
}else{
if(document.form.elements['gender[]'][idx].value=="any")
{
for (var idx1 = 0; idx1<max; idx1++) {
document.form.elements['gender[]'][idx1].checked=false;
}
}
}
}
}
function checkarray1(form) {
var total = 0;
var max = document.form.elements['gender[]'].length;
for (var idx = 0; idx<max; idx++) {
var cc=0;
if(document.form.elements['gender[]'][idx].checked==true)
{
if(document.form.elements['gender[]'][idx].value=="any")
{
cc=1;
}
}else{
if(document.form.elements['gender[]'][idx].value=="m")
{
document.form.elements['gender[]']['0'].checked=false;;
}
if(document.form.elements['gender[]'][idx].value=="f")
{
document.form.elements['gender[]']['0'].checked=false;;
}
}
}
}
</script>
</head>
<body>
<table class="right_linksr" width="100%" align="center" border="0" cellpadding="0" cellspacing="0">
<tbody><tr>
<td valign="middle" width="10%" align="left"><label>
<input size="5" name="gender[]" onclick="checkarray(this.form)" value="any" type="checkbox">
</label></td>
<td valign="middle" width="90%" align="left">Any Gender</td>
</tr>
<tr>
<td valign="middle" width="10%" align="left"><input name="gender[]" onclick="checkarray1(this.form)" value="f" type="checkbox"></td>
<td valign="middle" width="90%" align="left">Female</td>
</tr>
<tr>
<td valign="middle" width="10%" align="left"><input name="gender[]" onclick="checkarray1(this.form)" value="m" checked="checked/" type="checkbox"></td>
<td valign="middle" width="90%" align="left">Male</td>
</tr>
</tbody></table>
</body>
</html>
Here we have two javascripts function used. One function checkarray() selects all the checkboxes and the function checkarray1() unselects the any checkbox if any of the another checkbox is selected.
The below example would define how to write a javascript for a checkbox array.
<html>
<head>
<script language="javascript">
function checkarray(form) {
var total = 0;
var max = document.form.elements['gender[]'].length;
for (var idx = 0; idx<max; idx++) {
if(document.form.elements['gender[]'][idx].checked==true)
{
if(document.form.elements['gender[]'][idx].value=="any")
{
for (var idx1 = 0; idx1<max; idx1++) {
document.form.elements['gender[]'][idx1].checked=true;
}
}
}else{
if(document.form.elements['gender[]'][idx].value=="any")
{
for (var idx1 = 0; idx1<max; idx1++) {
document.form.elements['gender[]'][idx1].checked=false;
}
}
}
}
}
function checkarray1(form) {
var total = 0;
var max = document.form.elements['gender[]'].length;
for (var idx = 0; idx<max; idx++) {
var cc=0;
if(document.form.elements['gender[]'][idx].checked==true)
{
if(document.form.elements['gender[]'][idx].value=="any")
{
cc=1;
}
}else{
if(document.form.elements['gender[]'][idx].value=="m")
{
document.form.elements['gender[]']['0'].checked=false;;
}
if(document.form.elements['gender[]'][idx].value=="f")
{
document.form.elements['gender[]']['0'].checked=false;;
}
}
}
}
</script>
</head>
<body>
<table class="right_linksr" width="100%" align="center" border="0" cellpadding="0" cellspacing="0">
<tbody><tr>
<td valign="middle" width="10%" align="left"><label>
<input size="5" name="gender[]" onclick="checkarray(this.form)" value="any" type="checkbox">
</label></td>
<td valign="middle" width="90%" align="left">Any Gender</td>
</tr>
<tr>
<td valign="middle" width="10%" align="left"><input name="gender[]" onclick="checkarray1(this.form)" value="f" type="checkbox"></td>
<td valign="middle" width="90%" align="left">Female</td>
</tr>
<tr>
<td valign="middle" width="10%" align="left"><input name="gender[]" onclick="checkarray1(this.form)" value="m" checked="checked/" type="checkbox"></td>
<td valign="middle" width="90%" align="left">Male</td>
</tr>
</tbody></table>
</body>
</html>
Here we have two javascripts function used. One function checkarray() selects all the checkboxes and the function checkarray1() unselects the any checkbox if any of the another checkbox is selected.
Checkbox array Mutiple select
Generally in the checkbox, we have two different type of checkboxes one are plain checkboxes and the second one are checkbox array. The javascript for both differs a lot. The default checkbox script will be very simple to write and can be found any where in the net. The checkbox array scripts would be difficult.
The below example would define how to write a javascript for a checkbox array.
Example: Use checkbox array and have the option to checkall and uncheckall.
<html>
<head>
<script language="javascript">
function anyCheck(form) {
var total = 0;
var max = document.form.elements['list[]'].length;
for (var idx = 0; idx<max; idx++) {
if(document.form.elements['list[]'][idx].checked==true)
{
if(document.form.elements['list[]'][idx].value==1)
{
for (var idx1 = 0; idx1<max; idx1++) {
document.form.elements['list[]'][idx1].checked=true;
}
}
}else{
if(document.form.elements['list[]'][idx].value==1)
{
for (var idx1 = 0; idx1<max; idx1++) {
document.form.elements['list[]'][idx1].checked=false;
}
}
}
//alert(total);
}
//alert('ns');
//alert('ns');
//alert("You selected " + total + " boxes.");
}
</script>
</head>
<body>
<form name="form" action="test.html" method="post">
<input type="checkbox" name="list[]" value="1" onClick="anyCheck(this.form)">Checkall<br>
<input type="checkbox" name="list[]" value="2">Javascript<br>
<input type="checkbox" name="list[]" value="3">Active Server Pages<br>
<input type="checkbox" name="list[]" value="4">HTML<br>
<input type="checkbox" name="list[]" value="5">SQL<br>
</form>
</body>
The script anyCheck() function will validate the checkboxes.
The below example would define how to write a javascript for a checkbox array.
Example: Use checkbox array and have the option to checkall and uncheckall.
<html>
<head>
<script language="javascript">
function anyCheck(form) {
var total = 0;
var max = document.form.elements['list[]'].length;
for (var idx = 0; idx<max; idx++) {
if(document.form.elements['list[]'][idx].checked==true)
{
if(document.form.elements['list[]'][idx].value==1)
{
for (var idx1 = 0; idx1<max; idx1++) {
document.form.elements['list[]'][idx1].checked=true;
}
}
}else{
if(document.form.elements['list[]'][idx].value==1)
{
for (var idx1 = 0; idx1<max; idx1++) {
document.form.elements['list[]'][idx1].checked=false;
}
}
}
//alert(total);
}
//alert('ns');
//alert('ns');
//alert("You selected " + total + " boxes.");
}
</script>
</head>
<body>
<form name="form" action="test.html" method="post">
<input type="checkbox" name="list[]" value="1" onClick="anyCheck(this.form)">Checkall<br>
<input type="checkbox" name="list[]" value="2">Javascript<br>
<input type="checkbox" name="list[]" value="3">Active Server Pages<br>
<input type="checkbox" name="list[]" value="4">HTML<br>
<input type="checkbox" name="list[]" value="5">SQL<br>
</form>
</body>
The script anyCheck() function will validate the checkboxes.
Friday, April 3, 2009
Increase website font
This example mainly concentrates in the font of the web application. We use a default font in our websites and there may be situation we need to increase the font size of the text in the website. The example will help you to increase the font of your web application.
For using the example you need to download the javascript file and add place it in your folder. Call the javascript in the html or any page. Before using this javascript you need to to maintain the structure of the html. <body> tag must be started and as well as closed. You need to take care about this.
For using the example you need to download the javascript file and add place it in your folder. Call the javascript in the html or any page. Before using this javascript you need to to maintain the structure of the html. <body> tag must be started and as well as closed. You need to take care about this.
Monday, March 30, 2009
Ajax Tabs Content script
This is a versatile Ajax Tabs Content script that lets you display content pulled from external files inside a DIV and organized via CSS tabs. A fully unobtrusive, CSS and HTML based script, it supports practical features such as persistence of the active tab (ie: when page is reloaded), an "IFRAME" mode, a "slideshow" mode, ability to expand/contract arbitrary DIVs on the page at the same time, nested tabs, and much more.
Here's a quick outline of the script features:
* Fetch and display an external page (from the same domain) inside a container when a tab is clicked on via Ajax.
* (v 2.0) Apart from Ajax, an external page can also be fetched and displayed via the IFRAME element instead. This is useful for external pages that either contain JavaScript/ CSS code that doesn't run properly when fetched via Ajax, or the page is from an outside domain.
* Add a "default" content inside the container to either be shown while no tabs are selected, or to be associated with a specific tab. The default content is added inline on the page and not fetched via Ajax, to avoid unnecessary fetching of external pages.
* Supports session only persistence, so the last tab user clicked on is remembered if he/she returns to the page within the same browser session.
This is taken from dynamicdrive.com
SCREEN SHOT

Here's a quick outline of the script features:
* Fetch and display an external page (from the same domain) inside a container when a tab is clicked on via Ajax.
* (v 2.0) Apart from Ajax, an external page can also be fetched and displayed via the IFRAME element instead. This is useful for external pages that either contain JavaScript/ CSS code that doesn't run properly when fetched via Ajax, or the page is from an outside domain.
* Add a "default" content inside the container to either be shown while no tabs are selected, or to be associated with a specific tab. The default content is added inline on the page and not fetched via Ajax, to avoid unnecessary fetching of external pages.
* Supports session only persistence, so the last tab user clicked on is remembered if he/she returns to the page within the same browser session.
This is taken from dynamicdrive.com
SCREEN SHOT
Friday, March 27, 2009
Image slideshow with back and prev buttons
This script shows the image gallery slide show with prev and next buttons. When clicked in the next button the next 6 images are displayed. when clicked on the thumbnail the image is popuped up. First all the small thumbnails are displayed. When clicked on the thumbnail image is enlarged.
<span style="font-weight:bold;">Add thumbnails</span>
Thumbnails are inserted into the HTML code in the following format
<div class="strip_of_thumbnails"><div><a id="firstThumbnailLink" href="#" onclick="showPreview('images/image1_big.jpg',this);return false;"><img src="images/image1.jpg"></a></div><div><a href="#" onclick="showPreview('images/image2_big.jpg',this);return false;"><img src="images/image2.jpg"></a></div><div><a href="#" onclick="showPreview('images/image3_big.jpg',this);returnfalse;"><img src="images/image3.jpg"></a></div>
</div>
<div class="strip_of_thumbnails"> is the parent element of a vertical "strip" of thumbnails. How many thumbnails you add inside this div depends on your layout. In the demo, I have used 3 images.
Also note that id="firstThumbnailLink" is only applied to the first thumbnail. It is used to initially highlight this thumbnail
Layout
Width, height, border colors etc. are controlled by CSS. Look at the comment in image-slideshow-5.css for help.
Initialize the script
The slideshow script is initialized with these lines at the bottom of the HTML file:
<script type="text/javascript">
initGalleryScript(); // Initialize script
</script>
Speed of animations
You can control the speed of how fast the opacity changes on the large images, and how fast you want the thumbnail pane to slide when you click on the arrows. This is done by adjusting the javascript variables opacitySpeed, opacitySteps, slideSpeed and slideSteps at the top of image-slideshow-5.js.
Number of thumbnail columns
Usually, the script is able to measure how many columns of thumbnails you have automatically. However, if you have a slideshow where the script isn' table to show all your columns, you can set number of columns manually at the top of image-slideshow.js. This is done in the variable var columnsOfThumbnails
SCREENSHOT

<span style="font-weight:bold;">Add thumbnails</span>
Thumbnails are inserted into the HTML code in the following format
<div class="strip_of_thumbnails"><div><a id="firstThumbnailLink" href="#" onclick="showPreview('images/image1_big.jpg',this);return false;"><img src="images/image1.jpg"></a></div><div><a href="#" onclick="showPreview('images/image2_big.jpg',this);return false;"><img src="images/image2.jpg"></a></div><div><a href="#" onclick="showPreview('images/image3_big.jpg',this);returnfalse;"><img src="images/image3.jpg"></a></div>
</div>
<div class="strip_of_thumbnails"> is the parent element of a vertical "strip" of thumbnails. How many thumbnails you add inside this div depends on your layout. In the demo, I have used 3 images.
Also note that id="firstThumbnailLink" is only applied to the first thumbnail. It is used to initially highlight this thumbnail
Layout
Width, height, border colors etc. are controlled by CSS. Look at the comment in image-slideshow-5.css for help.
Initialize the script
The slideshow script is initialized with these lines at the bottom of the HTML file:
<script type="text/javascript">
initGalleryScript(); // Initialize script
</script>
Speed of animations
You can control the speed of how fast the opacity changes on the large images, and how fast you want the thumbnail pane to slide when you click on the arrows. This is done by adjusting the javascript variables opacitySpeed, opacitySteps, slideSpeed and slideSteps at the top of image-slideshow-5.js.
Number of thumbnail columns
Usually, the script is able to measure how many columns of thumbnails you have automatically. However, if you have a slideshow where the script isn' table to show all your columns, you can set number of columns manually at the top of image-slideshow.js. This is done in the variable var columnsOfThumbnails
SCREENSHOT
Wednesday, March 25, 2009
Javascript for Checkbox array
I have searched so many javascripts for writing a code for the checkbox array example "< input type="checkbox" name="check[]" >" But i could not find a single javascript. You will get so many scripts for a simple checkbox with name "check" , which can be found with a simple search, But this type of scenario's cannot be found easily. So we are updating the javascript so that you can use it when needed.
<html>
<head>
<script language="javascript">
function anyCheck(form) {
var total = 0;
var max = document.playlist.elements['ckbox[]'].length;
alert(max);
for (var idx = 0; idx < max; idx++) {
if(document.playlist.elements['ckbox[]'][idx].checked==true){
total += 1;
//alert(total);
}
//alert('ns');
}
alert("You selected " + total + " boxes.");
}
</script>
</head>
<body>
<form method="post" name=playlist>
1<input type=checkbox name=ckbox[]>
<brɮ<input type=checkbox name=ckbox[]>
<brɯ<input type=checkbox name=ckbox[]>
<brɰ<input type=checkbox name=ckbox[]>
<brɱ<input type=checkbox name=ckbox[]>
<brɲ<input type=checkbox name=ckbox[]>
<brɳ<input type=checkbox name=ckbox[]>
<brɴ<input type=checkbox name=ckbox[]>
<brɵ<input type=checkbox name=ckbox[]>
<p><input type=button value="Count Checkboxes" onClick="anyCheck(this.form)">
</form>
</body>
</html>
Here the method is used is anyCheck(). Which will invoke the javascript method. When we invoke the javascript method document.playlist.elements['ckbox[]'].length will calculate the length of the checkbox array value and if condition will evaluate which checkbox is checked and returns the total count.
<html>
<head>
<script language="javascript">
function anyCheck(form) {
var total = 0;
var max = document.playlist.elements['ckbox[]'].length;
alert(max);
for (var idx = 0; idx < max; idx++) {
if(document.playlist.elements['ckbox[]'][idx].checked==true){
total += 1;
//alert(total);
}
//alert('ns');
}
alert("You selected " + total + " boxes.");
}
</script>
</head>
<body>
<form method="post" name=playlist>
1<input type=checkbox name=ckbox[]>
<brɮ<input type=checkbox name=ckbox[]>
<brɯ<input type=checkbox name=ckbox[]>
<brɰ<input type=checkbox name=ckbox[]>
<brɱ<input type=checkbox name=ckbox[]>
<brɲ<input type=checkbox name=ckbox[]>
<brɳ<input type=checkbox name=ckbox[]>
<brɴ<input type=checkbox name=ckbox[]>
<brɵ<input type=checkbox name=ckbox[]>
<p><input type=button value="Count Checkboxes" onClick="anyCheck(this.form)">
</form>
</body>
</html>
Here the method is used is anyCheck(). Which will invoke the javascript method. When we invoke the javascript method document.playlist.elements['ckbox[]'].length will calculate the length of the checkbox array value and if condition will evaluate which checkbox is checked and returns the total count.
Monday, March 23, 2009
Tabs using javascript
This is the second example to creating the tabs in the html by using Div tag and the javascript.
The example will explain of how to create the tabs using div tag
<html>
<head>
<link rel="stylesheet" type="text/css" href="tabcontent.css" />
<script type="text/javascript" src="tabcontent.js">
</script>
</head>
<body>
<ul id="countrytabs" class="shadetabs">
<li><a href="#" rel="country1" class="selected">Tab 1</a></li>
<li><a href="#" rel="country2">Tab 2</a></li>
<li><a href="#" rel="country3">Tab 3</a></li>
<li><a href="#" rel="country4">Tab 4</a></li>
<li><a href="http://www.dynamicdrive.com">Dynamic Drive</a></li>
</ul>
<div style="border:1px solid gray; width:450px; margin-bottom: 1em; padding: 10px">
<div id="country1" class="tabcontent">
Tab content 1 here<br />Tab content 1 here<br />
</div>
<div id="country2" class="tabcontent">
Tab content 2 here<br />Tab content 2 here<br />
</div>
<div id="country3" class="tabcontent">
Tab content 3 here<br />Tab content 3 here<br />
</div>
<div id="country4" class="tabcontent">
Tab content 4 here<br />Tab content 4 here<br />
</div>
</div>
<script type="text/javascript">
var countries=new ddtabcontent("countrytabs")
countries.setpersist(true)
countries.setselectedClassTarget("link") //"link" or "linkparent"
countries.init()
</script>
<p><b><a href="javascript:countries.expandit(3)">Click here to select last tab</a></b></p>
</body>
</html>
To download the js and the css please click on the below link
Click here
The example will explain of how to create the tabs using div tag
<html>
<head>
<link rel="stylesheet" type="text/css" href="tabcontent.css" />
<script type="text/javascript" src="tabcontent.js">
</script>
</head>
<body>
<ul id="countrytabs" class="shadetabs">
<li><a href="#" rel="country1" class="selected">Tab 1</a></li>
<li><a href="#" rel="country2">Tab 2</a></li>
<li><a href="#" rel="country3">Tab 3</a></li>
<li><a href="#" rel="country4">Tab 4</a></li>
<li><a href="http://www.dynamicdrive.com">Dynamic Drive</a></li>
</ul>
<div style="border:1px solid gray; width:450px; margin-bottom: 1em; padding: 10px">
<div id="country1" class="tabcontent">
Tab content 1 here<br />Tab content 1 here<br />
</div>
<div id="country2" class="tabcontent">
Tab content 2 here<br />Tab content 2 here<br />
</div>
<div id="country3" class="tabcontent">
Tab content 3 here<br />Tab content 3 here<br />
</div>
<div id="country4" class="tabcontent">
Tab content 4 here<br />Tab content 4 here<br />
</div>
</div>
<script type="text/javascript">
var countries=new ddtabcontent("countrytabs")
countries.setpersist(true)
countries.setselectedClassTarget("link") //"link" or "linkparent"
countries.init()
</script>
<p><b><a href="javascript:countries.expandit(3)">Click here to select last tab</a></b></p>
</body>
</html>
To download the js and the css please click on the below link
Click here
Tabs using javascript
Here is an example to how to create a tab control in html using the div tag and the javascript
<script type="text/javascript" language="JavaScript"><!--
function ManageTabPanelDisplay() {
//
// Between the parenthesis, list the id's of the div's that
// will be affected when tabs are clicked. List in any
// order. Put the id's in single quotes (apostrophes)
// and separate them with a comma -- all one line.
//
var idlist = new Array('tab1focus','tab2focus','tab3focus','tab1ready','tab2ready','tab3ready','content1','content2','content3');
// No other customizations are necessary.
if(arguments.length < 1) { return; }
for(var i = 0; i < idlist.length; i++) {
var block = false;
for(var ii = 0; ii < arguments.length; ii++) {
if(idlist[i] == arguments[ii]) {
block = true;
break;
}
}
if(block) { document.getElementById(idlist[i]).style.display = "block"; }
else { document.getElementById(idlist[i]).style.display = "none"; }
}
}
//--></script>
<!-- Below is the CSS for the example tab panel div tags.
You may, of course, change these according to your
design requirements.
Refer to the Creating a Tab Panel article for notes
about this CSS. -->
<style type="text/css">
.tab {
font-family: verdana,sans-serif;
font-size: 14px;
width: 100px;
white-space: nowrap;
text-align: center;
border-style: solid;
border-color: black;
border-left-width: 1px;
border-right-width: 1px;
border-top-width: 1px;
border-bottom-width: 0px;
padding-top: 5px;
padding-bottom: 5px;
cursor: pointer;
}
.tabhold {
background-color: white;
color: black;
}
.tabfocus {
background-color: black;
color: white;
}
.tabcontent {
font-family: sans-serif;
font-size: 14px;
width: 400px;
height: 275px;
border-style: solid;
border-color: black;
border-width: 1px;
padding-top: 15px;
padding-left: 10px;
padding-right: 10px;
}
</style>
<!-- Below is the example tab panel. Notes are embedded in
the HTML, and the Creating a Tab Panel article also
contains information. -->
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td>
<div id="tab1focus" class="tab tabfocus" style="display:block;">
Tab1
</div>
<div id="tab1ready" class="tab tabhold" style="display:none;">
<!-- Between the parenthesis, provide a list of ids that are to
be visible when this tab is clicked. The ids are between
single quotes (apostrophes) and separated with a comma. -->
<span onclick="ManageTabPanelDisplay('tab1focus','tab2ready','tab3ready','content1')">Tab1</span>
</div>
</td><td width="20"> </td><td>
<div id="tab2focus" class="tab tabfocus" style="display:none;">
Tab2
</div>
<div id="tab2ready" class="tab tabhold" style="display:block;">
<!-- Between the parenthesis, provide a list of ids that are to
be visible when this tab is clicked. The ids are between
single quotes (apostrophes) and separated with a comma. -->
<span onclick="ManageTabPanelDisplay('tab1ready','tab2focus','tab3ready','content2')">Tab2</span>
</div>
</td><td width="20"> </td><td>
<div id="tab3focus" class="tab tabfocus" style="display:none;">
Tab3
</div>
<div id="tab3ready" class="tab tabhold" style="display:block;">
<!-- Between the parenthesis, provide a list of ids that are to
be visible when this tab is clicked. The ids are between
single quotes (apostrophes) and separated with a comma. -->
<span onclick="ManageTabPanelDisplay('tab1ready','tab2ready','tab3focus','content3')">Tab3</span>
</div>
</td><td width="180"> </td><td>
</tr>
<tr>
<td colspan="6">
<div id="content1" class="tabcontent" style="display:block;">
<p style="margin-top:0px">
This is the first tab
</p>
<p>
This tab is generated for the first tab data. Here you can have any data related to the first tab
</p>
<p>
WE can also have a paragraph of data, if we want to it to be
dynamically we need to concentrate more on this
</p>
<p>
blah................
</p>
<p style="margin-bottom:0px">
Tab1 sucessfully done
</p>
</div>
<div id="content2" class="tabcontent" style="display:none;">
<p style="margin-top:0px">
Hello everyone Now testing the contect2
</p>
<p>
This software is one of the most sophisticated form handlers available
on the Internet. Yet, it is easy to implement.
</p>
<p>
And it has anti-hijacking code built right in.
</p>
<p>
The software also helps spam-proof your web site so email
harvesting robots find nothing when they crawl your site.
</p>
<p style="margin-bottom:0px">
This is the sampel test program use this for the further resiults
</p>
</div>
<div id="content3" class="tabcontent" style="display:none;">
<div style="margin: 0px 20px 10px 0px; width: 80px; height: 105px; float: left;">Third tab test data</div>
<p style="margin-top:0px">
test data you can write anything here.
test datatest datatest datatest datatest data....... THis is the third tab
<p>
I noticed unusual activity on the server and determined a script
was being used to send spam. Quickly, I replaced that script with one that would
record everything sent to it but would not send email.
</p>
<p>
During the hijacking, which continued for hours, I developed and tweaked code to
block that very thing.<!-- The code was developed and tested and tweaked and tested
again, using the live hijacking to measure effectiveness.-->
</p>
<p>
Get some peace of mind. Get this
</p>
</div>
</td></tr>
</table>
<script type="text/javascript" language="JavaScript"><!--
function ManageTabPanelDisplay() {
//
// Between the parenthesis, list the id's of the div's that
// will be affected when tabs are clicked. List in any
// order. Put the id's in single quotes (apostrophes)
// and separate them with a comma -- all one line.
//
var idlist = new Array('tab1focus','tab2focus','tab3focus','tab1ready','tab2ready','tab3ready','content1','content2','content3');
// No other customizations are necessary.
if(arguments.length < 1) { return; }
for(var i = 0; i < idlist.length; i++) {
var block = false;
for(var ii = 0; ii < arguments.length; ii++) {
if(idlist[i] == arguments[ii]) {
block = true;
break;
}
}
if(block) { document.getElementById(idlist[i]).style.display = "block"; }
else { document.getElementById(idlist[i]).style.display = "none"; }
}
}
//--></script>
<!-- Below is the CSS for the example tab panel div tags.
You may, of course, change these according to your
design requirements.
Refer to the Creating a Tab Panel article for notes
about this CSS. -->
<style type="text/css">
.tab {
font-family: verdana,sans-serif;
font-size: 14px;
width: 100px;
white-space: nowrap;
text-align: center;
border-style: solid;
border-color: black;
border-left-width: 1px;
border-right-width: 1px;
border-top-width: 1px;
border-bottom-width: 0px;
padding-top: 5px;
padding-bottom: 5px;
cursor: pointer;
}
.tabhold {
background-color: white;
color: black;
}
.tabfocus {
background-color: black;
color: white;
}
.tabcontent {
font-family: sans-serif;
font-size: 14px;
width: 400px;
height: 275px;
border-style: solid;
border-color: black;
border-width: 1px;
padding-top: 15px;
padding-left: 10px;
padding-right: 10px;
}
</style>
<!-- Below is the example tab panel. Notes are embedded in
the HTML, and the Creating a Tab Panel article also
contains information. -->
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td>
<div id="tab1focus" class="tab tabfocus" style="display:block;">
Tab1
</div>
<div id="tab1ready" class="tab tabhold" style="display:none;">
<!-- Between the parenthesis, provide a list of ids that are to
be visible when this tab is clicked. The ids are between
single quotes (apostrophes) and separated with a comma. -->
<span onclick="ManageTabPanelDisplay('tab1focus','tab2ready','tab3ready','content1')">Tab1</span>
</div>
</td><td width="20"> </td><td>
<div id="tab2focus" class="tab tabfocus" style="display:none;">
Tab2
</div>
<div id="tab2ready" class="tab tabhold" style="display:block;">
<!-- Between the parenthesis, provide a list of ids that are to
be visible when this tab is clicked. The ids are between
single quotes (apostrophes) and separated with a comma. -->
<span onclick="ManageTabPanelDisplay('tab1ready','tab2focus','tab3ready','content2')">Tab2</span>
</div>
</td><td width="20"> </td><td>
<div id="tab3focus" class="tab tabfocus" style="display:none;">
Tab3
</div>
<div id="tab3ready" class="tab tabhold" style="display:block;">
<!-- Between the parenthesis, provide a list of ids that are to
be visible when this tab is clicked. The ids are between
single quotes (apostrophes) and separated with a comma. -->
<span onclick="ManageTabPanelDisplay('tab1ready','tab2ready','tab3focus','content3')">Tab3</span>
</div>
</td><td width="180"> </td><td>
</tr>
<tr>
<td colspan="6">
<div id="content1" class="tabcontent" style="display:block;">
<p style="margin-top:0px">
This is the first tab
</p>
<p>
This tab is generated for the first tab data. Here you can have any data related to the first tab
</p>
<p>
WE can also have a paragraph of data, if we want to it to be
dynamically we need to concentrate more on this
</p>
<p>
blah................
</p>
<p style="margin-bottom:0px">
Tab1 sucessfully done
</p>
</div>
<div id="content2" class="tabcontent" style="display:none;">
<p style="margin-top:0px">
Hello everyone Now testing the contect2
</p>
<p>
This software is one of the most sophisticated form handlers available
on the Internet. Yet, it is easy to implement.
</p>
<p>
And it has anti-hijacking code built right in.
</p>
<p>
The software also helps spam-proof your web site so email
harvesting robots find nothing when they crawl your site.
</p>
<p style="margin-bottom:0px">
This is the sampel test program use this for the further resiults
</p>
</div>
<div id="content3" class="tabcontent" style="display:none;">
<div style="margin: 0px 20px 10px 0px; width: 80px; height: 105px; float: left;">Third tab test data</div>
<p style="margin-top:0px">
test data you can write anything here.
test datatest datatest datatest datatest data....... THis is the third tab
<p>
I noticed unusual activity on the server and determined a script
was being used to send spam. Quickly, I replaced that script with one that would
record everything sent to it but would not send email.
</p>
<p>
During the hijacking, which continued for hours, I developed and tweaked code to
block that very thing.<!-- The code was developed and tested and tweaked and tested
again, using the live hijacking to measure effectiveness.-->
</p>
<p>
Get some peace of mind. Get this
</p>
</div>
</td></tr>
</table>
Saturday, March 21, 2009
Javascript radio button validation
In the form we need to like to have a scenario where we need to write a java script code for checking whether we need the radio has been selected or not?
The below example tells you to how to write a JavaScript for checking the radio button is checked or not.
<html>
<head>
<script language="javascript">
function GetSelectedItem() {
chosen = ""
len = document.f1.r1.length
for (i = 0; i <len; i++) {
if (document.f1.r1[i].checked) {
chosen = document.f1.r1[i].value
}
}
if (chosen == "") {
alert("No Location Chosen");
return false;
}
else {
alert(chosen)
return true;
}
}
</script>
</head>
<body>
<form name="f1" action="" onsubmit="return GetSelectedItem();">
<Input type ="radio" Name ="r1" Value = "NE">North East
<Input type = "radio" Name = "r1" Value = "NW">North West
<Input type = "radio" Name = "r1" Value = "SE">South East
<Input type = "radio" Name = "r1" Value = "SW">South West
<Input type = "radio" Name = "r1" Value = "midlands">Midlands
<input type="submit" value="submit">
</form>
</body>
</html>
Here we have a javascript method GetSelectedItem() which will be invoked when a submit button is pressed. document.f1.r1.length will tells the length of the radio buttons present. The for loop will check all the radio buttons and find if even a single radio button is checked or not.
The below example tells you to how to write a JavaScript for checking the radio button is checked or not.
<html>
<head>
<script language="javascript">
function GetSelectedItem() {
chosen = ""
len = document.f1.r1.length
for (i = 0; i <len; i++) {
if (document.f1.r1[i].checked) {
chosen = document.f1.r1[i].value
}
}
if (chosen == "") {
alert("No Location Chosen");
return false;
}
else {
alert(chosen)
return true;
}
}
</script>
</head>
<body>
<form name="f1" action="" onsubmit="return GetSelectedItem();">
<Input type ="radio" Name ="r1" Value = "NE">North East
<Input type = "radio" Name = "r1" Value = "NW">North West
<Input type = "radio" Name = "r1" Value = "SE">South East
<Input type = "radio" Name = "r1" Value = "SW">South West
<Input type = "radio" Name = "r1" Value = "midlands">Midlands
<input type="submit" value="submit">
</form>
</body>
</html>
Here we have a javascript method GetSelectedItem() which will be invoked when a submit button is pressed. document.f1.r1.length will tells the length of the radio buttons present. The for loop will check all the radio buttons and find if even a single radio button is checked or not.
Friday, March 20, 2009
Building a clock in Javascript
Clocks are one obvious application of timing loops.Below is the code for displaying a watch in a website using javascript
<html><head><title>A JavaScript Clock</title>
<script type = "text/javascript">
<!-- hide me from older browsers
var the_timeout;
function writeTime() {
// get a Date object
var today = new Date();
// ask the object for some information
var hours = today.getHours();
var minutes = today.getMinutes();
var seconds = today.getSeconds();
// make the minutes and seconds look right
minutes = fixTime(minutes);
seconds = fixTime(seconds);
// put together the time string and write it out
var the_time = hours + ":" + minutes + ":" + seconds;
window.document.the_form.the_text.value = the_time;
// run this function again in a second
the_timeout = setTimeout('writeTime();',1000);
}
function fixTime(the_time) {
if (the_time < 10)
{
the_time = "0" + the_time;
}
return the_time;
}
// show me -->
</script>
</head>
<body onload="writeTime();">
The time is now:
<form name = "the_form">
<input type = "text" name = "the_text">
<input type = "button" value = "Start the Clock" onClick = "writeTime();">
<input type = "button" value = "Stop the Clock"
onClick = "clearTimeout(the_timeout);">
</form>
</body>
</html>
The heart of script is the writeTime() function.Every second, this function figures out the current time, puts the time in the text field, and then sets a time-out to run writeTime() a second later.
the script starts by declaring the variable that will hold the timeouts. Next comes the writeTime() function, which creates a new Date
object in (remember that a new Date object holds the current date and time). Line and the two lines following it get the hours, minutes, and seconds from the Date object using the getHours(), getMinutes(), and getSeconds() methods.
you’ll see that getMinutes() and getSeconds() each return an integer from 1 to 59. If it’s two minutes and three seconds past 9 AM, the variable hours in will be 9, minutes will be 2, and seconds will be 3. But putting these numbers together to display the time would create the string 9:2:3 instead of 9:02:03. Line takes care of this little problem by sending the minutes and seconds variables to a function I’ve written called fixTime(). The fixTime() function in takes a number as its parameter and puts 0 before the number if it is less than 10 (so 2 becomes 02). Make sure you understand how the fixTime() and writeTime() functions work together.
Once fixTime() fixes the minutes and the seconds by inserting zero where appropriate, creates the time string, and writes it into the text box. Finally, sets the time-out that will call writeTime() again in one second. When writeTime() is called again, it creates a new Date object, gets the information out of it, fixes the minutes and seconds if necessary, writes the new time into the text box, and sets the time-out again. The whole process starts when a visitor clicks the Start the Clock button and ends when the visitor clicks the Stop the Clock button, which cancels the most recently set time-out.
<html><head><title>A JavaScript Clock</title>
<script type = "text/javascript">
<!-- hide me from older browsers
var the_timeout;
function writeTime() {
// get a Date object
var today = new Date();
// ask the object for some information
var hours = today.getHours();
var minutes = today.getMinutes();
var seconds = today.getSeconds();
// make the minutes and seconds look right
minutes = fixTime(minutes);
seconds = fixTime(seconds);
// put together the time string and write it out
var the_time = hours + ":" + minutes + ":" + seconds;
window.document.the_form.the_text.value = the_time;
// run this function again in a second
the_timeout = setTimeout('writeTime();',1000);
}
function fixTime(the_time) {
if (the_time < 10)
{
the_time = "0" + the_time;
}
return the_time;
}
// show me -->
</script>
</head>
<body onload="writeTime();">
The time is now:
<form name = "the_form">
<input type = "text" name = "the_text">
<input type = "button" value = "Start the Clock" onClick = "writeTime();">
<input type = "button" value = "Stop the Clock"
onClick = "clearTimeout(the_timeout);">
</form>
</body>
</html>
The heart of script is the writeTime() function.Every second, this function figures out the current time, puts the time in the text field, and then sets a time-out to run writeTime() a second later.
the script starts by declaring the variable that will hold the timeouts. Next comes the writeTime() function, which creates a new Date
object in (remember that a new Date object holds the current date and time). Line and the two lines following it get the hours, minutes, and seconds from the Date object using the getHours(), getMinutes(), and getSeconds() methods.
you’ll see that getMinutes() and getSeconds() each return an integer from 1 to 59. If it’s two minutes and three seconds past 9 AM, the variable hours in will be 9, minutes will be 2, and seconds will be 3. But putting these numbers together to display the time would create the string 9:2:3 instead of 9:02:03. Line takes care of this little problem by sending the minutes and seconds variables to a function I’ve written called fixTime(). The fixTime() function in takes a number as its parameter and puts 0 before the number if it is less than 10 (so 2 becomes 02). Make sure you understand how the fixTime() and writeTime() functions work together.
Once fixTime() fixes the minutes and the seconds by inserting zero where appropriate, creates the time string, and writes it into the text box. Finally, sets the time-out that will call writeTime() again in one second. When writeTime() is called again, it creates a new Date object, gets the information out of it, fixes the minutes and seconds if necessary, writes the new time into the text box, and sets the time-out again. The whole process starts when a visitor clicks the Start the Clock button and ends when the visitor clicks the Stop the Clock button, which cancels the most recently set time-out.
Creating arrays in javascript
Arrays are so handy that you’ll often want to create your own.for example, A phone book is an array of names and phone numbers. You can think of a survey as an array of questions; an array can also store the answers a visitor enters. A slide show is an array of pictures shown in sequence.
JavaScript lets you create your own arrays. If you know what
you want to store in the array when you create it, use a line like the following:
Array Declaration:
var colors =new Array("red", "orange", "yellow", "green", "blue", "indigo", "violet");
This line creates a variable called rainbow_colors that stores an array of colors.
The words new Array() tell JavaScript to create a new Array object.To put values in your new array, simply list them in the parentheses.
Example:
<html>
<head>
<title>Strobe</title>
<script type = "text/javascript">
function strobeIt()
{
var colors =
new Array("red", "orange", "yellow", "green", "blue", "indigo", "violet");
var index = 0;
while (index < rainbow_colors.length)
{
window.document.bgColor = colors[index];
index++;
}
}
</script>
</head>
<body>
<form>
<input type = "button" value = "strobe" onClick = "strobeIt();">
</form>
</body>
</html>
creates the array and sets up the loop, saying, “While index is less than the number of items in the array, execute the JavaScript between the curly brackets.” The first time through the loop, index is 0, so when looks up rainbow_colors[index], it gets the first item in the array, the value red. Line assigns this value to window.document.bgColor, which sets the background color to red. Once the script has set this color, adds 1 to index, and the loop begins again. Next time through, index will be 1, so will make the background color orange, then adds 1 to index, making it 2, and back through the loop we go. If you have a very fast computer, the background
may strobe too quickly for you to see it. In this case, add a few more colors
to the array in.
JavaScript lets you create your own arrays. If you know what
you want to store in the array when you create it, use a line like the following:
Array Declaration:
var colors =new Array("red", "orange", "yellow", "green", "blue", "indigo", "violet");
This line creates a variable called rainbow_colors that stores an array of colors.
The words new Array() tell JavaScript to create a new Array object.To put values in your new array, simply list them in the parentheses.
Example:
<html>
<head>
<title>Strobe</title>
<script type = "text/javascript">
function strobeIt()
{
var colors =
new Array("red", "orange", "yellow", "green", "blue", "indigo", "violet");
var index = 0;
while (index < rainbow_colors.length)
{
window.document.bgColor = colors[index];
index++;
}
}
</script>
</head>
<body>
<form>
<input type = "button" value = "strobe" onClick = "strobeIt();">
</form>
</body>
</html>
creates the array and sets up the loop, saying, “While index is less than the number of items in the array, execute the JavaScript between the curly brackets.” The first time through the loop, index is 0, so when looks up rainbow_colors[index], it gets the first item in the array, the value red. Line assigns this value to window.document.bgColor, which sets the background color to red. Once the script has set this color, adds 1 to index, and the loop begins again. Next time through, index will be 1, so will make the background color orange, then adds 1 to index, making it 2, and back through the loop we go. If you have a very fast computer, the background
may strobe too quickly for you to see it. In this case, add a few more colors
to the array in.
Thursday, March 19, 2009
Calenders in Javascript
The “Coolest” DHTML Calendar:
This tool is easy to use and is well documented. It has several high quality color themes and it's translated into a lot of languages.Easy to use in our websites. In the downloaded files each and everything is clearly explained with an example for further understanding.
Download link is:
Downloalink
Download this files and use in your website. I found is very usefull, Hope for youalso
This tool is easy to use and is well documented. It has several high quality color themes and it's translated into a lot of languages.Easy to use in our websites. In the downloaded files each and everything is clearly explained with an example for further understanding.
Download link is:
Downloalink
Download this files and use in your website. I found is very usefull, Hope for youalso
Monday, March 16, 2009
Javascript Menu List
In the below example we have a two list boxes where we can transfer one list box value to another list box. and vice verse. I found this useful when creating a distribution list where you have a set of people available to go into that list.
<html>
<head>
<script language="JavaScript">
<!--
function one2two() {
m1len = m1.length ;
for ( i=0; i<m1len ; i++){
if (m1.options[i].selected == true ) {
m2len = m2.length;
m2.options[m2len]= new Option(m1.options[i].text);
}
}
for ( i = (m1len -1); i>=0; i--){
if (m1.options[i].selected == true ) {
m1.options[i] = null;
}
}
}
function two2one() s{
m2len = m2.length ;
for ( i=0; i<m2len ; i++){
if (m2.options[i].selected == true ) {
m1len = m1.length;
m1.options[m1len]= new Option(m2.options[i].text);
}
}
for ( i=(m2len-1); i>=0; i--) {
if (m2.options[i].selected == true ) {
m2.options[i] = null;
}
}
}
//-->
</script>
</head>
<body>
form method="post" name="theForm">
<table align="center" bgcolor="white" border="1" cellpadding="10" cellspacing="0">
<tbody><tr><td align="center">
<select name="menu1" size="10" multiple="multiple">
<option>Menu Item 2</option>
<option>Menu Item 3</option>
<option>Menu Item 5</option>
</select><br>
<p align="center"><input onclick="one2two()" value=" >> " type="button"></p>
</td><td align="center">
<select name="menu2" size="10" multiple="multiple">
<option>Menu Item 6</option>
<option>Menu Item 4</option>
<option>Menu Item 1</option
</select><br>
<p align="center"><input onclick="two2one()" value=" << " type="button"></p>
</td></tr></tbody></table>
</form>
</body>
</html>
<html>
<head>
<script language="JavaScript">
<!--
function one2two() {
m1len = m1.length ;
for ( i=0; i<m1len ; i++){
if (m1.options[i].selected == true ) {
m2len = m2.length;
m2.options[m2len]= new Option(m1.options[i].text);
}
}
for ( i = (m1len -1); i>=0; i--){
if (m1.options[i].selected == true ) {
m1.options[i] = null;
}
}
}
function two2one() s{
m2len = m2.length ;
for ( i=0; i<m2len ; i++){
if (m2.options[i].selected == true ) {
m1len = m1.length;
m1.options[m1len]= new Option(m2.options[i].text);
}
}
for ( i=(m2len-1); i>=0; i--) {
if (m2.options[i].selected == true ) {
m2.options[i] = null;
}
}
}
//-->
</script>
</head>
<body>
form method="post" name="theForm">
<table align="center" bgcolor="white" border="1" cellpadding="10" cellspacing="0">
<tbody><tr><td align="center">
<select name="menu1" size="10" multiple="multiple">
<option>Menu Item 2</option>
<option>Menu Item 3</option>
<option>Menu Item 5</option>
</select><br>
<p align="center"><input onclick="one2two()" value=" >> " type="button"></p>
</td><td align="center">
<select name="menu2" size="10" multiple="multiple">
<option>Menu Item 6</option>
<option>Menu Item 4</option>
<option>Menu Item 1</option
</select><br>
<p align="center"><input onclick="two2one()" value=" << " type="button"></p>
</td></tr></tbody></table>
</form>
</body>
</html>
Thursday, March 12, 2009
Text / Image Slideshow
This is a simple basic example to slideshow the text given in an array. Here we use array to retrieve the text and pass to the slide show.
<html>
<head>
<title>Arrays and Loops</title>
<script type = "text/javascript">
var tips = new Array("Hello welcome.", "welcome to findmysolutions.blogspot.com", "Here you find a simple solutions.","javascript made simple","thanks you");
var index = 0;
function scroll() {
document.tip_form.tip_box.value = tips[index];
index++;
if (index == tips.length)
{
index = 0;
}
setTimeout("scroll()", 3500);
}
</script>
</head>
<body onLoad = "scroll();">
<form name = "tip_form">
<textarea name = "tip_box" rows = "3" cols = "30">
</form>
</body>
</html>
Here the text will be scrolled.
The same thing will be applied for the images the only change we need to do is just change the text value to the image path where the images are stored.
By adding the code <img src='test/testimage1.jpg'> ,<img src='test/testimage2.jpg'>
<img src='test/testimage3.jpg'> and so on. Then the images will be displayed instead of text.
<html>
<head>
<title>Arrays and Loops</title>
<script type = "text/javascript">
var tips = new Array("Hello welcome.", "welcome to findmysolutions.blogspot.com", "Here you find a simple solutions.","javascript made simple","thanks you");
var index = 0;
function scroll() {
document.tip_form.tip_box.value = tips[index];
index++;
if (index == tips.length)
{
index = 0;
}
setTimeout("scroll()", 3500);
}
</script>
</head>
<body onLoad = "scroll();">
<form name = "tip_form">
<textarea name = "tip_box" rows = "3" cols = "30">
</form>
</body>
</html>
Here the text will be scrolled.
The same thing will be applied for the images the only change we need to do is just change the text value to the image path where the images are stored.
By adding the code <img src='test/testimage1.jpg'> ,<img src='test/testimage2.jpg'>
<img src='test/testimage3.jpg'> and so on. Then the images will be displayed instead of text.
Select All / None Checkboxes
In the below example you will know how to enable all the checkboxes by using single click and how to disable the checkboxes by using a single click. These functionality is used when we need to delete all the records in a single page. The best usage of using this exampe is "In yahoo mail where we need to provide user to check all the read mail and delete"
<html>
<head>
<SCRIPT LANGUAGE="JavaScript">
function checkAll(field)
{
for (i = 0; i < field.length; i++)
field[i].checked = true ;
}
function uncheckAll(field)
{
for (i = 0; i < field.length; i++)
field[i].checked = false ;
}
</script>
</head>
<body>
<form name="myform" action="test2.html" method="post">
<b>Your Favorite Scripts & Languages</b><br>
<input type="checkbox" name="list" value="1">Java<br>
<input type="checkbox" name="list" value="2">Javascript<br>
<input type="checkbox" name="list" value="3">Active Server Pages<br>
<input type="checkbox" name="list" value="4">HTML<br>
<input type="checkbox" name="list" value="5">SQL<br>
<input type="button" name="CheckAll" value="Check All"
onClick="checkAll(document.myform.list)">
<input type="button" name="UnCheckAll" value="Uncheck All"
onClick="uncheckAll(document.myform.list)">
<br>
</form>
</body>
</html>
Here when we click on the check All function all the checkboxes are selected and when the uncheckAll() function is selected then all the checkboxes are deselected
If you want to use a single button to checkall and uncheck all use the below code
<html>
<head>
<script language="javascript">
checked=false;
function checkedAll (frm1) {
var aa= document.getElementById('frm1');
if (checked == false)
{
checked = true
}
else
{
checked = false
}
for (var i =0; i < aa.elements.length; i++)
{
aa.elements[i].checked = checked;
}
}
</script>
</head>
<body>
<form id ="frm1">
<input type="checkbox" name="chk1">
<input type="checkbox" name="chk2">
<input type="checkbox" name="chk3">
<input type="checkbox" name="chk4">
<input type="checkbox" name="chk5">
<input type='button' name='checkall' value="check/uncheck" onclick='checkedAll(frm1);'>
</form>
</body>
</html>
<html>
<head>
<SCRIPT LANGUAGE="JavaScript">
function checkAll(field)
{
for (i = 0; i < field.length; i++)
field[i].checked = true ;
}
function uncheckAll(field)
{
for (i = 0; i < field.length; i++)
field[i].checked = false ;
}
</script>
</head>
<body>
<form name="myform" action="test2.html" method="post">
<b>Your Favorite Scripts & Languages</b><br>
<input type="checkbox" name="list" value="1">Java<br>
<input type="checkbox" name="list" value="2">Javascript<br>
<input type="checkbox" name="list" value="3">Active Server Pages<br>
<input type="checkbox" name="list" value="4">HTML<br>
<input type="checkbox" name="list" value="5">SQL<br>
<input type="button" name="CheckAll" value="Check All"
onClick="checkAll(document.myform.list)">
<input type="button" name="UnCheckAll" value="Uncheck All"
onClick="uncheckAll(document.myform.list)">
<br>
</form>
</body>
</html>
Here when we click on the check All function all the checkboxes are selected and when the uncheckAll() function is selected then all the checkboxes are deselected
If you want to use a single button to checkall and uncheck all use the below code
<html>
<head>
<script language="javascript">
checked=false;
function checkedAll (frm1) {
var aa= document.getElementById('frm1');
if (checked == false)
{
checked = true
}
else
{
checked = false
}
for (var i =0; i < aa.elements.length; i++)
{
aa.elements[i].checked = checked;
}
}
</script>
</head>
<body>
<form id ="frm1">
<input type="checkbox" name="chk1">
<input type="checkbox" name="chk2">
<input type="checkbox" name="chk3">
<input type="checkbox" name="chk4">
<input type="checkbox" name="chk5">
<input type='button' name='checkall' value="check/uncheck" onclick='checkedAll(frm1);'>
</form>
</body>
</html>
checkbox validation
There are so many ways to check the checkbox validation scripts. But in some scenarios we need to check the checkbox's selected or not dynamically, for which the general scenarios are not usefull.
The below javascript code is used for checking the N number of checkbox's dynamically but not calling each and every checkbox name individually.
Javascript example:
<html>
<head>
<script language="javascript">
function ValidateCheckboxForm(checkForm){
var count = 0;
for(var i=0; i< checkForm.length; i++){
if(checkForm[i].checked == true){
count++;
}
}
if(count <= 0){
alert("please select at least one checkbox");
return false;
}
}
</script>
</head>
<body>
<form name="checkform">
<input type="checkbox" name="a" value="a" />A
<input type="checkbox" name="b" value="b" />B
<input type="checkbox" name="c" value="c" />C
<input type="button" name="submitmail" value="Click Here" onclick="javascript:ValidateCheckboxForm(this.form)"/> </form>
</body>
</html>
Here function name is "ValidateCheckboxForm()"
if user did not check even a single check box then an alert message is provided "to check atleast one check box" else it returns true.
The below javascript code is used for checking the N number of checkbox's dynamically but not calling each and every checkbox name individually.
Javascript example:
<html>
<head>
<script language="javascript">
function ValidateCheckboxForm(checkForm){
var count = 0;
for(var i=0; i< checkForm.length; i++){
if(checkForm[i].checked == true){
count++;
}
}
if(count <= 0){
alert("please select at least one checkbox");
return false;
}
}
</script>
</head>
<body>
<form name="checkform">
<input type="checkbox" name="a" value="a" />A
<input type="checkbox" name="b" value="b" />B
<input type="checkbox" name="c" value="c" />C
<input type="button" name="submitmail" value="Click Here" onclick="javascript:ValidateCheckboxForm(this.form)"/> </form>
</body>
</html>
Here function name is "ValidateCheckboxForm()"
if user did not check even a single check box then an alert message is provided "to check atleast one check box" else it returns true.
Monday, March 9, 2009
Navigation using the Select tag
By using the form select tag the user can easily navigate from one page to another page. The "windiow.location.href" is used to move the user from one page to the another page. The below code makes it so simple.
<html>
<head>
<script language="JavaScript" type="text/JavaScript">
function changePage(newLoc)
{
nextPage = newLoc.options[newLoc.selectedIndex].value;
if (nextPage != "")
{
document.location.href = nextPage
}
}
</script>
</head>
<body>
<center>
<form method="POST" name="menu" >
<select name="selectedPage" onChange="changePage(this.form.selectedPage)">
<option value = "" selected> select </option>
<option value = "/test.html"> Goto test page </option>
<option value = "/home.html"> Goto home page </option>
<option value = "/welcome.html"> Goto welcome page </option>
<option value = "/index.html"> Goto index page </option>
</select>
</form>
</center>
</body>
</html>
Here as per the selected the option value the URL will be refreshed and the particular page is displayed.
<html>
<head>
<script language="JavaScript" type="text/JavaScript">
function changePage(newLoc)
{
nextPage = newLoc.options[newLoc.selectedIndex].value;
if (nextPage != "")
{
document.location.href = nextPage
}
}
</script>
</head>
<body>
<center>
<form method="POST" name="menu" >
<select name="selectedPage" onChange="changePage(this.form.selectedPage)">
<option value = "" selected> select </option>
<option value = "/test.html"> Goto test page </option>
<option value = "/home.html"> Goto home page </option>
<option value = "/welcome.html"> Goto welcome page </option>
<option value = "/index.html"> Goto index page </option>
</select>
</form>
</center>
</body>
</html>
Here as per the selected the option value the URL will be refreshed and the particular page is displayed.
Reading values from select tag
The below examples provides you information of how to read the values from the select tag
<html>
<head>
<script language="JavaScript">
<!--//
function Message(form)
{
if (form.MySelect.options[form.MySelect.selectedIndex].value=='none')
//This is the basic code to select what to do depending on the option.
{
}// We do nothing if the first selection is chosen.
else
if (form.MySelect.options[form.MySelect.options.selectedIndex].value=='welcome')
{
alert('Welcome to javascript solutions');
}
else
if (form.MySelect.options[form.MySelect.options.selectedIndex].value=='hello')
{
alert('Hello, how are you!');
}
}
//-->
</script>
<title>Select Boxes</title>
</head>
<body>
<form>
<p><select name="MySelect" size="1">
<option selected value="none">Clicke to test</option>
<option value="welcome">Welcome to javascript</option>
<option value="hello">hello world</option>
</select><input type="button" value="clickme >>>" name="B1"
onClick="Message(this.form)"></p>
</form>
</body>
</html>
<html>
<head>
<script language="JavaScript">
<!--//
function Message(form)
{
if (form.MySelect.options[form.MySelect.selectedIndex].value=='none')
//This is the basic code to select what to do depending on the option.
{
}// We do nothing if the first selection is chosen.
else
if (form.MySelect.options[form.MySelect.options.selectedIndex].value=='welcome')
{
alert('Welcome to javascript solutions');
}
else
if (form.MySelect.options[form.MySelect.options.selectedIndex].value=='hello')
{
alert('Hello, how are you!');
}
}
//-->
</script>
<title>Select Boxes</title>
</head>
<body>
<form>
<p><select name="MySelect" size="1">
<option selected value="none">Clicke to test</option>
<option value="welcome">Welcome to javascript</option>
<option value="hello">hello world</option>
</select><input type="button" value="clickme >>>" name="B1"
onClick="Message(this.form)"></p>
</form>
</body>
</html>
Saturday, March 7, 2009
Validations for checking only numerics
The javascript below checks whether the user has entered numeric value or alphabets in the text box. Here we used the onkeyup event to raise the javascript event.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>
<script>
function checkForInvalid(obj) {
if( /[^0-9\-]|-{2,}/gi.test(obj.value) ) {
alert("Invalid character in Invoice No.")
obj.focus();
obj.select();
return false;
}
return true;
}
</script>
</head>
<body>
<form name="myForm">
<input type="text" name="invoiceNo" onkeyup="checkForInvalid(this)">
</form>
</body>
</html>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>
<script>
function checkForInvalid(obj) {
if( /[^0-9\-]|-{2,}/gi.test(obj.value) ) {
alert("Invalid character in Invoice No.")
obj.focus();
obj.select();
return false;
}
return true;
}
</script>
</head>
<body>
<form name="myForm">
<input type="text" name="invoiceNo" onkeyup="checkForInvalid(this)">
</form>
</body>
</html>
Validations for only characters
The below code allows user to enter only the character(lower case or upper case)
function check(df)
{
for (n=0;n<document.form.elements.length-1;n++)
{
if(form.elements[n].name.indexOf("invoiceNo")!=-1) && (form.elements[n].value==""))
{
var flag
var flag="false"
var valid="abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ";
for(i=0;i<form.elements[n].value.length;i++)
{
if(valid.indexOf(form.elements[n].value.charAt(i))==-1)
{
flag="true"
alert("Invalid character in Invoice No.")
form.elements[n].focus();
form.elements[n].select();
return false;
break;
}
}
}
}
}
function check(df)
{
for (n=0;n<document.form.elements.length-1;n++)
{
if(form.elements[n].name.indexOf("invoiceNo")!=-1) && (form.elements[n].value==""))
{
var flag
var flag="false"
var valid="abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ";
for(i=0;i<form.elements[n].value.length;i++)
{
if(valid.indexOf(form.elements[n].value.charAt(i))==-1)
{
flag="true"
alert("Invalid character in Invoice No.")
form.elements[n].focus();
form.elements[n].select();
return false;
break;
}
}
}
}
}
Thursday, March 5, 2009
Javascript Form events
Some Events That Different Form Elements Can Handle
These are the common events which we mostly use
For Button:
we use the Onclick event
For Check box:
We use the onClick event
For radio Button:
We use the onClick event
For Text Box:
We use the onChange event
Note that text fields, textareas, and selects can trigger events only when
someone changes them. If a user clicks on a pull-down menu and then chooses
an already selected option, that doesn’t trigger the onChange event. Similarly,
if someone clicks a text field and then clicks somewhere else without changing
anything in the text field, onChange won’t register this action.
Notice also that the form element takes an event called onSubmit. A form
is submitted when the user presses the ENTER key with the cursor in a text field
or when the user clicks a submit button.
Textbox simple onchange event example:
<form name = "the_form"
>
<input type = "text" name = "email"
onChange = "checkEmail(window.document.the_form.email.value);"/>
</form>
the elements window.document.the_form.email inside the onChange simply identify the text field that the onChange is part of. Because the text field is sending its own value to the checkEmail() function, the onChange of the text field can be rewritten like this:
onChange = "checkEmail(this.value);"
Simple example for SELECT TAG
<html>
<head>
<title>A Pull-Down Menu for Navigation</title>
<script type = "text/javascript">
<!-- hide me from older browsers
function visitSite(the_site)
{
window.location = the_site;
}
// show me -->
</script>
</head>
<body>
<h1>Use the pull-down menu to choose where you want to go</h1>
<form name = "the_form">
<select name = "the_select" onChange = "visitSite(this.value);">
<option value = "http://www.nostarch.com">No Starch Press</option>
<option value = "http://www.nytimes.com">The New York Times</option>
<option value = "http://www.theonion.com">The Onion</option>
</select></form>
</body>
</html>
These are the common events which we mostly use
For Button:
we use the Onclick event
For Check box:
We use the onClick event
For radio Button:
We use the onClick event
For Text Box:
We use the onChange event
Note that text fields, textareas, and selects can trigger events only when
someone changes them. If a user clicks on a pull-down menu and then chooses
an already selected option, that doesn’t trigger the onChange event. Similarly,
if someone clicks a text field and then clicks somewhere else without changing
anything in the text field, onChange won’t register this action.
Notice also that the form element takes an event called onSubmit. A form
is submitted when the user presses the ENTER key with the cursor in a text field
or when the user clicks a submit button.
Textbox simple onchange event example:
<form name = "the_form"
>
<input type = "text" name = "email"
onChange = "checkEmail(window.document.the_form.email.value);"/>
</form>
the elements window.document.the_form.email inside the onChange simply identify the text field that the onChange is part of. Because the text field is sending its own value to the checkEmail() function, the onChange of the text field can be rewritten like this:
onChange = "checkEmail(this.value);"
Simple example for SELECT TAG
<html>
<head>
<title>A Pull-Down Menu for Navigation</title>
<script type = "text/javascript">
<!-- hide me from older browsers
function visitSite(the_site)
{
window.location = the_site;
}
// show me -->
</script>
</head>
<body>
<h1>Use the pull-down menu to choose where you want to go</h1>
<form name = "the_form">
<select name = "the_select" onChange = "visitSite(this.value);">
<option value = "http://www.nostarch.com">No Starch Press</option>
<option value = "http://www.nytimes.com">The New York Times</option>
<option value = "http://www.theonion.com">The Onion</option>
</select></form>
</body>
</html>
Tuesday, March 3, 2009
Image Zoom in/out
We have so many image zoom in /zoom out functionality, But in this we make is so simpler and make it compatible with so many browsers with less javascript.
Highslide JS
Highslide JS is an open source JavaScript software, offering a Web 2.0 approach to popup windows. It streamlines the use of thumbnail images and HTML popups on web pages. The library offers these features and advantages:
* No plugins like Flash or Java required.
* Popup blockers are no problem. The content expands within the active browser window.
* Single click. After opening the image or HTML popup, the user can scroll further down or leave the page without closing it.
* Compatibility and safe fallback. If the user has disabled JavaScript or is using an old browser, the browser redirects directly to the image itself or to a fallback HTML page.
URL for this is highslide
You can visit the above URL and download the free script code. In this site we have so many zoom in/out scripts used which are so user friendly and can be easily implemented.
Installation
Note: some basic HTML knowledge is required to install Highslide.
1. Download and extract the zip-archive from the download page.
2. Run the file index.html, navigate to your favourite setup and view the source.
3. Change the file to suit your needs, or copy and paste parts of it into your HTML file. If you mess it up, go back to the original file and change it bit by bit. Study the documentation and the API reference for advanced features.
4. If you move the Highslide JS files, remember to change the graphicsDir setting in the Javascript.
Highslide JS
Highslide JS is an open source JavaScript software, offering a Web 2.0 approach to popup windows. It streamlines the use of thumbnail images and HTML popups on web pages. The library offers these features and advantages:
* No plugins like Flash or Java required.
* Popup blockers are no problem. The content expands within the active browser window.
* Single click. After opening the image or HTML popup, the user can scroll further down or leave the page without closing it.
* Compatibility and safe fallback. If the user has disabled JavaScript or is using an old browser, the browser redirects directly to the image itself or to a fallback HTML page.
URL for this is highslide
You can visit the above URL and download the free script code. In this site we have so many zoom in/out scripts used which are so user friendly and can be easily implemented.
Installation
Note: some basic HTML knowledge is required to install Highslide.
1. Download and extract the zip-archive from the download page.
2. Run the file index.html, navigate to your favourite setup and view the source.
3. Change the file to suit your needs, or copy and paste parts of it into your HTML file. If you mess it up, go back to the original file and change it bit by bit. Study the documentation and the API reference for advanced features.
4. If you move the Highslide JS files, remember to change the graphicsDir setting in the Javascript.
Monday, March 2, 2009
How to read values in a form - Radio Buttons
The code for reading and setting radio buttons is slightly more complicated
than for text fields and checkboxes. Because all the radio buttons in a group
have the same name, you can’t just ask about the settings for a radio button
with a certain name—JavaScript won’t know which button you mean.
To overcome this difficulty, JavaScript puts all of the radio buttons with
the same name in a list. Each radio button in the list is given a number. The
first radio button in the group is number 0, the second is 1, the third is 2, and
so on. (Most programming languages start counting from 0—you just have
to get used to this.)
To refer to a radio button, use the notation radio_button_name[item_number].
For example, if you have four radio buttons named age, the first one will be
age[0], the second will be age[1], the third age[2], and the fourth age[3].
To see whether a visitor has chosen a certain radio button, look at its
checked property, just as with checkboxes. Let’s say you have four radio buttons
named age in a form called radio_button_form.To test whether
your visitor has selected the first radio button in the age group, write something
like this:
if (window.document.radio_button_form.age[0].checked == true)
{
alert("the first radio button was selected!");
}
This is much the same method that you would use for a checkbox. The only difference is that you must refer to the first radio button in the age group as age[0], whereas with a checkbox you can just give its name. Once you know how to determine whether a radio button is checked, it’s easy to understand how to select a radio button with JavaScript. With checkboxes, you use something like this:
window.document.form_name.checkbox_name.checked = true;
<b>Pull-Down Menus and Scrollable Lists<#60/b>
JavaScript can read and set pull-down menus and scrollable lists as it does radio buttons, with two main differences. First, while radio buttons have a checked property, pull-down menus and scrollable lists have a comparable property called selected. Second, the list that keeps track of the options in a pull-down menu or scrollable list differs from that for a radio button. As discussed in the section on reading and setting radio buttons, when a browser sees a group of radio buttons, it creates a list with the same name as the set
of radio buttons.
In contrast, a pull-down menu or scrollable list has the options property,
a list of all the options in the pull-down or scrollable list, which can tell you
what’s selected in that menu or list.
Small Example:
<form name = "my_form">
<select name = "the_gender">
<option value = "male">Male</option>
<option value = "female">Female</option>
</select>
</form>
The javascript function for this is:
if (window.document.my_form.the_gender.options[0].selected == true)
{
alert("It's a boy!)";
}
You can also select an option:
window.document.my_form.the_gender.options[1].selected = true;
Executing this line of JavaScript would select the female option in the pulldown
menu. Sometimes you have a long list of options in a pull-down menu, you just want to know which one the visitor has selected. Happily, pulldown menus and scrollable lists have a value property that contains value of the selected option.out quickly whether a visitor chose male or female in this pull-down menu,write something like this:
var chosen_gender = window.document.my_form.the_gender.value;
than for text fields and checkboxes. Because all the radio buttons in a group
have the same name, you can’t just ask about the settings for a radio button
with a certain name—JavaScript won’t know which button you mean.
To overcome this difficulty, JavaScript puts all of the radio buttons with
the same name in a list. Each radio button in the list is given a number. The
first radio button in the group is number 0, the second is 1, the third is 2, and
so on. (Most programming languages start counting from 0—you just have
to get used to this.)
To refer to a radio button, use the notation radio_button_name[item_number].
For example, if you have four radio buttons named age, the first one will be
age[0], the second will be age[1], the third age[2], and the fourth age[3].
To see whether a visitor has chosen a certain radio button, look at its
checked property, just as with checkboxes. Let’s say you have four radio buttons
named age in a form called radio_button_form.To test whether
your visitor has selected the first radio button in the age group, write something
like this:
if (window.document.radio_button_form.age[0].checked == true)
{
alert("the first radio button was selected!");
}
This is much the same method that you would use for a checkbox. The only difference is that you must refer to the first radio button in the age group as age[0], whereas with a checkbox you can just give its name. Once you know how to determine whether a radio button is checked, it’s easy to understand how to select a radio button with JavaScript. With checkboxes, you use something like this:
window.document.form_name.checkbox_name.checked = true;
<b>Pull-Down Menus and Scrollable Lists<#60/b>
JavaScript can read and set pull-down menus and scrollable lists as it does radio buttons, with two main differences. First, while radio buttons have a checked property, pull-down menus and scrollable lists have a comparable property called selected. Second, the list that keeps track of the options in a pull-down menu or scrollable list differs from that for a radio button. As discussed in the section on reading and setting radio buttons, when a browser sees a group of radio buttons, it creates a list with the same name as the set
of radio buttons.
In contrast, a pull-down menu or scrollable list has the options property,
a list of all the options in the pull-down or scrollable list, which can tell you
what’s selected in that menu or list.
Small Example:
<form name = "my_form">
<select name = "the_gender">
<option value = "male">Male</option>
<option value = "female">Female</option>
</select>
</form>
The javascript function for this is:
if (window.document.my_form.the_gender.options[0].selected == true)
{
alert("It's a boy!)";
}
You can also select an option:
window.document.my_form.the_gender.options[1].selected = true;
Executing this line of JavaScript would select the female option in the pulldown
menu. Sometimes you have a long list of options in a pull-down menu, you just want to know which one the visitor has selected. Happily, pulldown menus and scrollable lists have a value property that contains value of the selected option.out quickly whether a visitor chose male or female in this pull-down menu,write something like this:
var chosen_gender = window.document.my_form.the_gender.value;
Sunday, March 1, 2009
How to read values in a form - Checkbox
Checkboxes differ from text fields and textareas. Instead of having a value
as text fields and textareas do, they have a Boolean attribute called checked.
If a user has clicked a checkbox so that an × or check mark appears in
it, then checked equals true. If the checkbox is not on, then checked equals
false (remember—because true and false are Booleans, they don’t take
quotes).
Let me explain with an example:
<html>
<head>
<title>A Little Quiz</title>
<script type = "text/javascript">
<!-- hide me from older browsers
function scoreQuiz()
{
var correct = 0;
if (window.document.the_form.question1.checked == true) {
correct = correct + 1;
}
if (window.document.the_form.question2.checked == true) {
correct = correct + 1;
}
if (window.document.the_form.question3.checked == false) {
correct = correct + 1;
}
alert("You got " + correct + " answers right!");
}
// show me -->
</script>
</head>
<body>
<h1>A Little Quiz</h1>
Check the statements which are true:
<form name = "the_form">
<input type = "checkbox" name =
"question1"> All men are featherless bipeds<br>
<input type = "checkbox" name =
"question2"> All kangaroos are featherless bipeds<<br>
<input type = "checkbox" name = "question3"> All men are kangaroos<br>
<input type = "button" value = "score this quiz" onClick = "scoreQuiz();">
</form>
</body>
</html>
When a user clicks the button form element at the bottom of the window it calls the scoreQuiz() function. then creates a variable called correct and sets its value to 0. This variable keeps track of how many answers the visitor answered correctly.
The if-then statement in is slightly different from the other two. It says that if the checked property of the third checkbox is false (that is, the visitor
hasn’t selected the checkbox), then JavaScript should add 1 to correct.
To show visitors the correct answers after they click the score button we could use the scoreQuiz() function to determine the value of each checkbox by setting its checked property to true or false. updates the scoreQuiz() function to give the correct answers.
I add an else to each if-then clause, which sets the checkbox to the correct answer if the visitor gets the answer wrong. The first if-then clause, starting with , reads in plain English, “If the visitor checks the first checkbox, the answer is correct, so add 1 to the variable correct. Otherwise, check the first checkbox to indicate the correct answer.” If the visitor guessed wrong, selects the first checkbox by setting its checked property to true.
as text fields and textareas do, they have a Boolean attribute called checked.
If a user has clicked a checkbox so that an × or check mark appears in
it, then checked equals true. If the checkbox is not on, then checked equals
false (remember—because true and false are Booleans, they don’t take
quotes).
Let me explain with an example:
<html>
<head>
<title>A Little Quiz</title>
<script type = "text/javascript">
<!-- hide me from older browsers
function scoreQuiz()
{
var correct = 0;
if (window.document.the_form.question1.checked == true) {
correct = correct + 1;
}
if (window.document.the_form.question2.checked == true) {
correct = correct + 1;
}
if (window.document.the_form.question3.checked == false) {
correct = correct + 1;
}
alert("You got " + correct + " answers right!");
}
// show me -->
</script>
</head>
<body>
<h1>A Little Quiz</h1>
Check the statements which are true:
<form name = "the_form">
<input type = "checkbox" name =
"question1"> All men are featherless bipeds<br>
<input type = "checkbox" name =
"question2"> All kangaroos are featherless bipeds<<br>
<input type = "checkbox" name = "question3"> All men are kangaroos<br>
<input type = "button" value = "score this quiz" onClick = "scoreQuiz();">
</form>
</body>
</html>
When a user clicks the button form element at the bottom of the window it calls the scoreQuiz() function. then creates a variable called correct and sets its value to 0. This variable keeps track of how many answers the visitor answered correctly.
The if-then statement in is slightly different from the other two. It says that if the checked property of the third checkbox is false (that is, the visitor
hasn’t selected the checkbox), then JavaScript should add 1 to correct.
To show visitors the correct answers after they click the score button we could use the scoreQuiz() function to determine the value of each checkbox by setting its checked property to true or false. updates the scoreQuiz() function to give the correct answers.
I add an else to each if-then clause, which sets the checkbox to the correct answer if the visitor gets the answer wrong. The first if-then clause, starting with , reads in plain English, “If the visitor checks the first checkbox, the answer is correct, so add 1 to the variable correct. Otherwise, check the first checkbox to indicate the correct answer.” If the visitor guessed wrong, selects the first checkbox by setting its checked property to true.
How to read values in a form - Textbox
Important thing we have to know before we write a javascript form is "The values are are reading must be with the tag". The values which are in between them can only be read. IF the elements are outer than this form then that variables are not accessible.
Simple example:
<html>
<head>
<title>A Very Simple Calculator</title>
<script type = "text/javascript">
<!-- hide me from older browsers
function multiplyTheFields()
{
var number_one = window.document.the_form.field_one.value;
var number_two = window.document.the_form.field_two.value;
var product = number_one * number_two;
window.document.the_form.the_answer.value = product;
}
// show me -->
</script>
</head>
<body>
<form name = "the_form">
Number 1: <input type = "text" name = "field_one"> <br>
Number 2: <input type = "text" name = "field_two"> <br>
The Product: <input type = "text" name = "the_answer"> <br>
<a href = "#" onClick = "multiplyTheFields(); return false;">Multiply them!</a>
</form>
</body>
</html>
Here is a simple example which takes the values from the two text boxes .. mutiply them and display the resultant value to the third text box.
Note: In the last step of the JavaScript function we see return false. Here return false is mentioned because the form should not be posted and page should not be refreshed.
Simple example:
<html>
<head>
<title>A Very Simple Calculator</title>
<script type = "text/javascript">
<!-- hide me from older browsers
function multiplyTheFields()
{
var number_one = window.document.the_form.field_one.value;
var number_two = window.document.the_form.field_two.value;
var product = number_one * number_two;
window.document.the_form.the_answer.value = product;
}
// show me -->
</script>
</head>
<body>
<form name = "the_form">
Number 1: <input type = "text" name = "field_one"> <br>
Number 2: <input type = "text" name = "field_two"> <br>
The Product: <input type = "text" name = "the_answer"> <br>
<a href = "#" onClick = "multiplyTheFields(); return false;">Multiply them!</a>
</form>
</body>
</html>
Here is a simple example which takes the values from the two text boxes .. mutiply them and display the resultant value to the third text box.
Note: In the last step of the JavaScript function we see return false. Here return false is mentioned because the form should not be posted and page should not be refreshed.
Saturday, February 21, 2009
Pop Up window Properties
Window Properties
1.The status Property
One of the most useful (and most abused) properties is the window’s status.
The value of this property defines what appears in the window’s status bar. One common status is the URL of a link you are mousing over.
You can use the status property to change what appears in the status bar. You may have noticed that some people put a kind of marquee in this area, scrolling across the bottom with messages like Buy our stuff! Buy our stuff! I don’t want to encourage status bar abuse, so I’m not going to teach you exactly how to do that, but you can use these JavaScript techniques to create a similar effect. To change what appears in the status bar of a window, use a <body> tag like this:
<body onLoad = "window.status = 'hi there!';">
This tag tells JavaScript to change the contents of the window’s status bar after the page has been fully loaded into the browser.
You might want to use the status property to inform visitors about the site they’ll see if they click a link. For example, if you have a link to a very graphics-intensive site, the words Warning: This site has a lot of graphics could appear in the status bar when the visitor mouses over the link. You can set this up with an onMouseOver:
<a href = "http://www.myheavygraphicsite.com/" onMouseOver =
"window.status='Warning: This site has a lot of graphics'; return true;">
My Heavy Graphic Site</a>
2. The opener PropertyThe opener Property
When one window opens a new window, the new window remembers its parent (the original window) using the opener property. An opened window can access its parent through this property and then manipulate the parent. For example, if you want a link in the new window to change the contents of the status bar in the original window, you’d include the following code inside a link in the new window:
<a href = "#" onClick = "var my_parent = window.opener; my_parent.status='howdy'; return false;">put howdy into the status bar of the original window</a>
The first statement inside the onClick says, “Find the window that opened me, and set the variable my_parent to point to that window.” The second statement changes the status property of that window to howdy.
Or you can make this simple
put howdy into the status bar of the original window
3. More Window Methods :
You’ve seen four window methods so far: open(), close(), focus(), and blur().
Let’s look at two more that come in handy from time to time: resizing and moving windows.
Resizing Windows
Modern browsers provide two different ways your JavaScript can resize a window. The window.resizeTo() method resizes a window to a given width and height. To change a small window into one that’s 500 pixels wide and 200 pixels high, you’d use the following script:
window.resizeTo(500,200);
Alternatively, you can change the size of a window by a specific amount using window.resizeBy(). The window.resizeBy() method takes two numbers: how much the width of the window should change and how much the height should change.
The code window.resizeBy(10, -5);makes a browser 10 pixels wider and 5 pixels shorter.
Moving Windows
The window.moveTo() method moves a window to an absolute position on the screen. If you want the window in the upper-left corner of the user’s screen, you’d type:
window.moveTo(0,0);
The first number is the number of pixels from the left border of the screen you want the window’s upper-left corner to appear, and the second number is the number of pixels from the top of the screen.
An alternative to window.moveTo() is window.moveBy(). If you want to move a window 5 pixels to the right and 10 pixels down from its current position, you’d type:
window.moveBy(5,10);
The first number is the number of pixels to the right you want to move the window, and the second is the number of pixels down. If you want to move the window 10 pixels up and 5 to the left, just use negative numbers:
window.moveBy(-5,-10);
Be careful not to move a window entirely off a user’s screen. To ensure
against this possibility, you have to know the size of the user’s screen. The two
properties that indicate this are:
window.screen.availHeight
window.screen.availWidth
TO calculate a particular point in a page we can use
var left_point = parseInt(width / 2) - parseInt(window_width / 2);
1.The status Property
One of the most useful (and most abused) properties is the window’s status.
The value of this property defines what appears in the window’s status bar. One common status is the URL of a link you are mousing over.
You can use the status property to change what appears in the status bar. You may have noticed that some people put a kind of marquee in this area, scrolling across the bottom with messages like Buy our stuff! Buy our stuff! I don’t want to encourage status bar abuse, so I’m not going to teach you exactly how to do that, but you can use these JavaScript techniques to create a similar effect. To change what appears in the status bar of a window, use a <body> tag like this:
<body onLoad = "window.status = 'hi there!';">
This tag tells JavaScript to change the contents of the window’s status bar after the page has been fully loaded into the browser.
You might want to use the status property to inform visitors about the site they’ll see if they click a link. For example, if you have a link to a very graphics-intensive site, the words Warning: This site has a lot of graphics could appear in the status bar when the visitor mouses over the link. You can set this up with an onMouseOver:
<a href = "http://www.myheavygraphicsite.com/" onMouseOver =
"window.status='Warning: This site has a lot of graphics'; return true;">
My Heavy Graphic Site</a>
2. The opener PropertyThe opener Property
When one window opens a new window, the new window remembers its parent (the original window) using the opener property. An opened window can access its parent through this property and then manipulate the parent. For example, if you want a link in the new window to change the contents of the status bar in the original window, you’d include the following code inside a link in the new window:
<a href = "#" onClick = "var my_parent = window.opener; my_parent.status='howdy'; return false;">put howdy into the status bar of the original window</a>
The first statement inside the onClick says, “Find the window that opened me, and set the variable my_parent to point to that window.” The second statement changes the status property of that window to howdy.
Or you can make this simple
put howdy into the status bar of the original window
3. More Window Methods :
You’ve seen four window methods so far: open(), close(), focus(), and blur().
Let’s look at two more that come in handy from time to time: resizing and moving windows.
Resizing Windows
Modern browsers provide two different ways your JavaScript can resize a window. The window.resizeTo() method resizes a window to a given width and height. To change a small window into one that’s 500 pixels wide and 200 pixels high, you’d use the following script:
window.resizeTo(500,200);
Alternatively, you can change the size of a window by a specific amount using window.resizeBy(). The window.resizeBy() method takes two numbers: how much the width of the window should change and how much the height should change.
The code window.resizeBy(10, -5);makes a browser 10 pixels wider and 5 pixels shorter.
Moving Windows
The window.moveTo() method moves a window to an absolute position on the screen. If you want the window in the upper-left corner of the user’s screen, you’d type:
window.moveTo(0,0);
The first number is the number of pixels from the left border of the screen you want the window’s upper-left corner to appear, and the second number is the number of pixels from the top of the screen.
An alternative to window.moveTo() is window.moveBy(). If you want to move a window 5 pixels to the right and 10 pixels down from its current position, you’d type:
window.moveBy(5,10);
The first number is the number of pixels to the right you want to move the window, and the second is the number of pixels down. If you want to move the window 10 pixels up and 5 to the left, just use negative numbers:
window.moveBy(-5,-10);
Be careful not to move a window entirely off a user’s screen. To ensure
against this possibility, you have to know the size of the user’s screen. The two
properties that indicate this are:
window.screen.availHeight
window.screen.availWidth
TO calculate a particular point in a page we can use
var left_point = parseInt(width / 2) - parseInt(window_width / 2);
Monday, February 16, 2009
Working with Window Objects
Because windows are objects, you manipulate them just as you would any object.by using
JavaScript’s dot notation to apply one of the available methods to the window object you name:
window_name.method_name();
1. Opening Windows :
To open a window, use the open() method, which opens a window that has the characteristics you specify as parameters inside its parentheses:
var window_name =window.open("some_url", "html_name",feature1,feature2,feature3,...");
In this example, I’ve set up a variable called window_name to refer to the window we’re opening. When I want to use JavaScript to change or manipulate what’s inside the window, I’ll refer to this window as window_name. Here window_name is just a variable—you could use any valid JavaScript variable name, such as fido, in its place if you so desired
2.Manipulating the Appearance of New Windows :
The three parameters of the window.open() command control the new
window’s characteristics.
a) The URL Parameter : The first parameter is the URL of the page you want to appear inside the window when the window opens. If you’d like to open a window with the Book of JavaScript website, inside the <script> tags you’d write:
var window_name = window.open("http://www.bookofjavascript.com/", "html_name");
b) The HTML Name Parameter : The HTML name of the window (the second parameter inside the parentheses) is useful only if you want to load a page into the window when the user clicks an HTML link on a different page. For example, if you open a window using window.open() and use the second parameter to name the window my_window, you can then use an HTML link to load a page into your new window. To do this, put the HTML name of the new window into the
target attribute of the link. For example, clicking the following link loads the Webmonkey site into my_window:
<a href = "http://www.webmonkey.com/" target = "my_window">Put Webmonkey into my new window!</a>
You can also use the target element of the link tag to open windows without using JavaScript. For example, if a visitor clicks a link like the one above and you haven’t already opened a window named my_window with JavaScript, your browser opens a new window and loads the link. The downside to opening a window without using JavaScript is that you have no control over what the window looks like, and you can’t change it once you’ve opened it (except by loading another page into it from a link).
c) The Features Parameter : The third parameter in the window.open() command is a list of features that let you control what the new window will look like. This is where things start to get fun.
The features parameter lets you open a new window that includes all, some, or none of these features. If you leave out the third parameter (that is, you list just the first two parameters and nothing more—not even empty quotes), the window you open will have all the features you see and will be the same size as the previous window. However, if you list any of the features in the third parameter, only the listed features appear in the window you open. So if you open a window with the command
var book_of_javascript_window =window.open("http://www.bookofjavascript.com/","book_of_javascript", "resizable");
you’ll get a resizable window with the Book of JavaScript site in it. This window
will be the same size as the window from which you opened it, but will lack
the menu bar, status bar, scroll bars, and other features
If you want more than one feature, you can list them inside the quotes, separated by commas. Make sure to leave all spaces out of this string. For some reason, spaces inside a feature string cause some browsers to draw your windows incorrectly.
var pictures =window.open("http://bookofjavascript.com", book_of_javascript","width=605,height=350" );
Feature Effect
directories Adds buttons such as What’s New and What’s Cool to the menu bar. Some
browsers ignore this feature. Others add different buttons.
height = X Adjusts the height of the window to X pixels.
left = X Places the new window’s left border X pixels from the left edge of
the screen.
location Adds a location bar, where the site visitor can enter URLs.
menubar Adds a menu bar.
resizable Controls whether the visitor can resize the window; all Mac windows are
resizable even if you leave this feature out.
scrollbars Adds scroll bars if the contents of the page are bigger than the
window.
status Adds a status bar to the bottom of the window. Use the status
property of the window object, discussed later in this chapter, to
define what will be displayed in the status bar.
Toolbar Adds a standard toolbar with buttons such as back, forward, and stop.
Which buttons are added depends on the browser being used.
top = X Places the window’s top border X pixels from the top edge of the
screen.
width = X Adjusts the window width to X pixels.
JavaScript’s dot notation to apply one of the available methods to the window object you name:
window_name.method_name();
1. Opening Windows :
To open a window, use the open() method, which opens a window that has the characteristics you specify as parameters inside its parentheses:
var window_name =window.open("some_url", "html_name",feature1,feature2,feature3,...");
In this example, I’ve set up a variable called window_name to refer to the window we’re opening. When I want to use JavaScript to change or manipulate what’s inside the window, I’ll refer to this window as window_name. Here window_name is just a variable—you could use any valid JavaScript variable name, such as fido, in its place if you so desired
2.Manipulating the Appearance of New Windows :
The three parameters of the window.open() command control the new
window’s characteristics.
a) The URL Parameter : The first parameter is the URL of the page you want to appear inside the window when the window opens. If you’d like to open a window with the Book of JavaScript website, inside the <script> tags you’d write:
var window_name = window.open("http://www.bookofjavascript.com/", "html_name");
b) The HTML Name Parameter : The HTML name of the window (the second parameter inside the parentheses) is useful only if you want to load a page into the window when the user clicks an HTML link on a different page. For example, if you open a window using window.open() and use the second parameter to name the window my_window, you can then use an HTML link to load a page into your new window. To do this, put the HTML name of the new window into the
target attribute of the link. For example, clicking the following link loads the Webmonkey site into my_window:
<a href = "http://www.webmonkey.com/" target = "my_window">Put Webmonkey into my new window!</a>
You can also use the target element of the link tag to open windows without using JavaScript. For example, if a visitor clicks a link like the one above and you haven’t already opened a window named my_window with JavaScript, your browser opens a new window and loads the link. The downside to opening a window without using JavaScript is that you have no control over what the window looks like, and you can’t change it once you’ve opened it (except by loading another page into it from a link).
c) The Features Parameter : The third parameter in the window.open() command is a list of features that let you control what the new window will look like. This is where things start to get fun.
The features parameter lets you open a new window that includes all, some, or none of these features. If you leave out the third parameter (that is, you list just the first two parameters and nothing more—not even empty quotes), the window you open will have all the features you see and will be the same size as the previous window. However, if you list any of the features in the third parameter, only the listed features appear in the window you open. So if you open a window with the command
var book_of_javascript_window =window.open("http://www.bookofjavascript.com/","book_of_javascript", "resizable");
you’ll get a resizable window with the Book of JavaScript site in it. This window
will be the same size as the window from which you opened it, but will lack
the menu bar, status bar, scroll bars, and other features
If you want more than one feature, you can list them inside the quotes, separated by commas. Make sure to leave all spaces out of this string. For some reason, spaces inside a feature string cause some browsers to draw your windows incorrectly.
var pictures =window.open("http://bookofjavascript.com", book_of_javascript","width=605,height=350" );
Feature Effect
directories Adds buttons such as What’s New and What’s Cool to the menu bar. Some
browsers ignore this feature. Others add different buttons.
height = X Adjusts the height of the window to X pixels.
left = X Places the new window’s left border X pixels from the left edge of
the screen.
location Adds a location bar, where the site visitor can enter URLs.
menubar Adds a menu bar.
resizable Controls whether the visitor can resize the window; all Mac windows are
resizable even if you leave this feature out.
scrollbars Adds scroll bars if the contents of the page are bigger than the
window.
status Adds a status bar to the bottom of the window. Use the status
property of the window object, discussed later in this chapter, to
define what will be displayed in the status bar.
Toolbar Adds a standard toolbar with buttons such as back, forward, and stop.
Which buttons are added depends on the browser being used.
top = X Places the window’s top border X pixels from the top edge of the
screen.
width = X Adjusts the window width to X pixels.
Monday, February 9, 2009
Triggering Events in Javascript
JavaScript we’ve seen is triggered when a web page loads into a browser. But JavaScript can also be event driven. Event-driven JavaScript waits for your visitor to take a particular action, such as mousing over an image, before it reacts. The key to coding eventdriven JavaScript is to know the names of events and how to use them.
Event Types
With JavaScript’s help, different parts of your web page can detect different
events. For example, a pull-down menu can know when it has changed, a window when it has closed and a link when a visitor has clicked on it. In this chapter I’ll focus on link events.
A link can detect many kinds of events, all of which involve interactions with the mouse. The link can detect when your mouse moves over it and when your mouse moves off of it. The link knows when you click down on it, and whether, while you’re over the link, you lift your finger back off the button after clicking down. The link also knows whether the mouse moves while over the link
1. Onclick:
Before adding JavaScript:
<a href = "http://www.bookofjavascript.com/">Visit the Book of JavaScript
website</a>
After adding JavaScript:
<a href = "http://www.bookofjavascript.com/"
onClick = "alert('Off to the Book of JavaScript!');">Visit the Book of
JavaScript website</a>
Try putting the link with the onClick into one of your own web pages.When you click the link, an alert box should come up and say Off to the Book of JavaScript!. When you click OK in the box, the page should load the Book of JavaScript website.
Notice that, aside from the addition of onClick, this enhanced link is
almost exactly like the normal link. The onClick event handler says, “When
this link is clicked, pop up an alert.”
2. onMouseOver and onMouseOut
Two other link events are onMouseOver and onMouseOut. Moving the mouse over
a link triggers onMouseOver,
<a href = "#" onMouseOver = "alert('Mayday! Mouse overboard!');">board</a>
As you can see, moving the mouse over the link triggers onMouseOver. The
code for onMouseOut looks like the onMouseOver code (except for the handler
name) and is triggered when the mouse moves off of the link. You can use
onMouseOut, onMouseOver, and onClick in the same link.
<a href = "#"
onMouseOver = "alert('Mayday! Mouse overboard!');"
onMouseOut = "alert('Hooray! Mouse off of board!!');"
onClick = "return false;">
board
</a>
Mousing over this link results in an alert box showing the words Mayday! Mouse overboard!. Pressing ENTER to get rid of the first alert and moving your mouse off the link results in another alert box that contains the words Hooray! Mouse off of board!! If you click the link instead of moving your mouse off it, nothing will happen, because of the return false, code in the onClick.
3. onMouseMove, onMouseUp, and onMouseDown
The onMouseMove, onMouseUp, and onMouseDown event handlers work much like the others. Try them yourself and see. The onMouseMove event handler is called whenever the mouse is moved while it is over the link. The onMouseDown event handler is triggered when a mouse button is pressed down while the mouse is over a link. Similarly, the onMouseUp event handler is triggered when the mouse button is lifted up again. An onClick event handler is triggered whenever an onMouseDown event is followed by an onMouseUp event.
4. Quotes in JavaScript
<script>script</> The only exception to this rule is when JavaScript is inside the quotes of an event. Your browser will assume that anything within these quotes is JavaScript, so you shouldn’t put <script> and </script> tags
in there.
Also note that the quotes in the alert are single quotes ('). If these were
double quotes ("), JavaScript wouldn’t be able to figure out which quotes go
with what. For example, if you wrote
onClick = "alert("Off to the Book of JavaScript!");"
JavaScript would think that the second double quote closed the first one, which would confuse it and result in an error. Make sure that if you have quotes inside quotes, one set is double and the other is single.
Problem with Apostrophes
Apostrophes can also pose problems.
Example:
onClick = "alert('Here's the Book of JavaScript page. You're gonna love it!');"
Unfortunately, JavaScript reads the apostrophes in Here's and You're as single quotes inside single quotes and gets confused. If you really want those apostrophes, escape them with a backslash (\), like this:
onClick = "alert('Here\'s the Book of JavaScript page. You\'re gonna love it!');"
Putting a backslash before a special character, such as a quote, tells
JavaScript to print the item rather than interpret it.
Change Background color
A simple script to change the background color is
<a href = "#"
onClick = "var the_color = prompt('red or blue?','');
window.document.bgColor = the_color;
return false;">
When you click this link, a prompt box asks whether you want to change
the background to red or blue. When you type your response, the background
changes to that color. In fact, you can type whatever you want into that prompt
box, and your browser will try to guess the color you mean. (You can even do
a kind of personality exam by typing your name into the prompt and seeing
what color your browser thinks you are. When I type then This example demonstrates two new facts about JavaScript.
First, notice that the onClick triggers three separate JavaScript statements. You can put as many lines of JavaScript as you want between the onClick’s quotes, although if you put too much in there, the HTML starts to look messy.
Second, notice that you can change the background color of a page by setting window.document.bgColor to the color you desire. To make the background of a page red, you’d type:
window.document.bgColor = 'red';
Event Types
With JavaScript’s help, different parts of your web page can detect different
events. For example, a pull-down menu can know when it has changed, a window when it has closed and a link when a visitor has clicked on it. In this chapter I’ll focus on link events.
A link can detect many kinds of events, all of which involve interactions with the mouse. The link can detect when your mouse moves over it and when your mouse moves off of it. The link knows when you click down on it, and whether, while you’re over the link, you lift your finger back off the button after clicking down. The link also knows whether the mouse moves while over the link
1. Onclick:
Before adding JavaScript:
<a href = "http://www.bookofjavascript.com/">Visit the Book of JavaScript
website</a>
After adding JavaScript:
<a href = "http://www.bookofjavascript.com/"
onClick = "alert('Off to the Book of JavaScript!');">Visit the Book of
JavaScript website</a>
Try putting the link with the onClick into one of your own web pages.When you click the link, an alert box should come up and say Off to the Book of JavaScript!. When you click OK in the box, the page should load the Book of JavaScript website.
Notice that, aside from the addition of onClick, this enhanced link is
almost exactly like the normal link. The onClick event handler says, “When
this link is clicked, pop up an alert.”
2. onMouseOver and onMouseOut
Two other link events are onMouseOver and onMouseOut. Moving the mouse over
a link triggers onMouseOver,
<a href = "#" onMouseOver = "alert('Mayday! Mouse overboard!');">board</a>
As you can see, moving the mouse over the link triggers onMouseOver. The
code for onMouseOut looks like the onMouseOver code (except for the handler
name) and is triggered when the mouse moves off of the link. You can use
onMouseOut, onMouseOver, and onClick in the same link.
<a href = "#"
onMouseOver = "alert('Mayday! Mouse overboard!');"
onMouseOut = "alert('Hooray! Mouse off of board!!');"
onClick = "return false;">
board
</a>
Mousing over this link results in an alert box showing the words Mayday! Mouse overboard!. Pressing ENTER to get rid of the first alert and moving your mouse off the link results in another alert box that contains the words Hooray! Mouse off of board!! If you click the link instead of moving your mouse off it, nothing will happen, because of the return false, code in the onClick.
3. onMouseMove, onMouseUp, and onMouseDown
The onMouseMove, onMouseUp, and onMouseDown event handlers work much like the others. Try them yourself and see. The onMouseMove event handler is called whenever the mouse is moved while it is over the link. The onMouseDown event handler is triggered when a mouse button is pressed down while the mouse is over a link. Similarly, the onMouseUp event handler is triggered when the mouse button is lifted up again. An onClick event handler is triggered whenever an onMouseDown event is followed by an onMouseUp event.
4. Quotes in JavaScript
<script>script</> The only exception to this rule is when JavaScript is inside the quotes of an event. Your browser will assume that anything within these quotes is JavaScript, so you shouldn’t put <script> and </script> tags
in there.
Also note that the quotes in the alert are single quotes ('). If these were
double quotes ("), JavaScript wouldn’t be able to figure out which quotes go
with what. For example, if you wrote
onClick = "alert("Off to the Book of JavaScript!");"
JavaScript would think that the second double quote closed the first one, which would confuse it and result in an error. Make sure that if you have quotes inside quotes, one set is double and the other is single.
Problem with Apostrophes
Apostrophes can also pose problems.
Example:
onClick = "alert('Here's the Book of JavaScript page. You're gonna love it!');"
Unfortunately, JavaScript reads the apostrophes in Here's and You're as single quotes inside single quotes and gets confused. If you really want those apostrophes, escape them with a backslash (\), like this:
onClick = "alert('Here\'s the Book of JavaScript page. You\'re gonna love it!');"
Putting a backslash before a special character, such as a quote, tells
JavaScript to print the item rather than interpret it.
Change Background color
A simple script to change the background color is
<a href = "#"
onClick = "var the_color = prompt('red or blue?','');
window.document.bgColor = the_color;
return false;">
When you click this link, a prompt box asks whether you want to change
the background to red or blue. When you type your response, the background
changes to that color. In fact, you can type whatever you want into that prompt
box, and your browser will try to guess the color you mean. (You can even do
a kind of personality exam by typing your name into the prompt and seeing
what color your browser thinks you are. When I type then This example demonstrates two new facts about JavaScript.
First, notice that the onClick triggers three separate JavaScript statements. You can put as many lines of JavaScript as you want between the onClick’s quotes, although if you put too much in there, the HTML starts to look messy.
Second, notice that you can change the background color of a page by setting window.document.bgColor to the color you desire. To make the background of a page red, you’d type:
window.document.bgColor = 'red';
Thursday, February 5, 2009
Functions in Javascript
There are so many functions in Javascript, I am describing which are used most in common
1. alert(): One handy function is alert(), which puts a string into a little announcement box
Basic Syntax is alert("string value"); which is defined in the javascript declaration to display a pop up with your selected value.
2. prompt(): The built in function, which asks your visitor for some information and then sets a variable equal to whatever your visitor types.
Example:
<html>
<head>
<title>A Form Letter</title>
< script type="text/javascript" language="javascript">
var the_name = prompt("What's your name?", "Enter your name here");
</script>
</head>
<body>
<h1>Dear
<script type = "text/javascript">
document.write(the_name);
</script>
</body>
</html>
3. Date():
The syntax to call the date in the javascript is
var now = new Date();
It creates an Object that store data that require multiple pieces of information, such as a particular moment in time. For example, in JavaScript you need an object to
describe 2:30 PM on Saturday, January 7, 2006, in San Francisco. That’s because it requires many different bits of information: the time, day, month, date, and year, as well as some representation (in relation to Greenwich Mean Time) of the user’s local time.
Using this object we can retrieve all the values we need
a. For Year : get the year of the date stored in the variable now.
Example: var the_year = now.getYear();
b. For Date : Returns the day of the month as an integer from 1 to 31
Example: var the_Date = now.getDate();
c. For Day : Returns day of the week as an integer where 0 is Sunday and 1 is
Monday
Example: var the_Day = now.getDay();
d. For getHour : Returns the hour as an integer between 0 and 23
Example: var the_hours = now.getHours();
e. For Minutes : Returns the minutes as an integer between 0 and 59
Example: var the_minutes = now.getMinutes();
f. For Month : Return the month as an integer between 0 and 11 where 0 is January
and 11 is December
Example: var the_month = now.getMonth();
g. For Seconds : Returns the seconds as an integer between 0 and 59
Example: var the_seconds = now.getSeconds();
h. For Time : Returns the current time in milliseconds where 0 is January 1, 1970,
00:00:00
Example: var the_time = now.getTime();
i. For Year : Returns the year, but this format differs from browser to browser
Exampe: now.getYear();
4. navigator.appName: This function determines which browser you are using
Example:
var browser_name = navigator.appName;
If you are using mozilla then browser_name outputs "mozilla"
If you are using netscape then browser_name outputs "netscape"
It also uses another function to determine the browser properties getBrowser();
Example:
var browser_info = getBrowser();
var browser_name = browserInfo[0];
var browser_version = browserInfo[1];
5. For Redirecting the Users:
Using javascript we can redirect users from one page to another page.
Syntax:
window.location.href ="http://www.mywebsite.testpage.html";
1. alert(): One handy function is alert(), which puts a string into a little announcement box
Basic Syntax is alert("string value"); which is defined in the javascript declaration to display a pop up with your selected value.
2. prompt(): The built in function, which asks your visitor for some information and then sets a variable equal to whatever your visitor types.
Example:
<html>
<head>
<title>A Form Letter</title>
< script type="text/javascript" language="javascript">
var the_name = prompt("What's your name?", "Enter your name here");
</script>
</head>
<body>
<h1>Dear
<script type = "text/javascript">
document.write(the_name);
</script>
</body>
</html>
3. Date():
The syntax to call the date in the javascript is
var now = new Date();
It creates an Object that store data that require multiple pieces of information, such as a particular moment in time. For example, in JavaScript you need an object to
describe 2:30 PM on Saturday, January 7, 2006, in San Francisco. That’s because it requires many different bits of information: the time, day, month, date, and year, as well as some representation (in relation to Greenwich Mean Time) of the user’s local time.
Using this object we can retrieve all the values we need
a. For Year : get the year of the date stored in the variable now.
Example: var the_year = now.getYear();
b. For Date : Returns the day of the month as an integer from 1 to 31
Example: var the_Date = now.getDate();
c. For Day : Returns day of the week as an integer where 0 is Sunday and 1 is
Monday
Example: var the_Day = now.getDay();
d. For getHour : Returns the hour as an integer between 0 and 23
Example: var the_hours = now.getHours();
e. For Minutes : Returns the minutes as an integer between 0 and 59
Example: var the_minutes = now.getMinutes();
f. For Month : Return the month as an integer between 0 and 11 where 0 is January
and 11 is December
Example: var the_month = now.getMonth();
g. For Seconds : Returns the seconds as an integer between 0 and 59
Example: var the_seconds = now.getSeconds();
h. For Time : Returns the current time in milliseconds where 0 is January 1, 1970,
00:00:00
Example: var the_time = now.getTime();
i. For Year : Returns the year, but this format differs from browser to browser
Exampe: now.getYear();
4. navigator.appName: This function determines which browser you are using
Example:
var browser_name = navigator.appName;
If you are using mozilla then browser_name outputs "mozilla"
If you are using netscape then browser_name outputs "netscape"
It also uses another function to determine the browser properties getBrowser();
Example:
var browser_info = getBrowser();
var browser_name = browserInfo[0];
var browser_version = browserInfo[1];
5. For Redirecting the Users:
Using javascript we can redirect users from one page to another page.
Syntax:
window.location.href ="http://www.mywebsite.testpage.html";
Subscribe to:
Posts (Atom)