| JavaScript in Action - Examples |
| Example: Background Color Change. |
| The Code: |
<form>
<input type="button" value="Green" name="b1" onClick="document.body.style.backgroundColor='green'">
<input type="button" value="Red" name="b2" onClick="document.body.style.backgroundColor='red'">
<input type="button" value="White" name="b3" onClick="document.body.style.backgroundColor='white'">
</form>
|
| Note on HTML "color" attribute values: |
For the "color" attribute, we can specify 16 values by the name
itself, like white, black, grean, teal, fuchsia, silver ...
|
| Example: Set some text in the brower's status bar. |
| Place your mouse here and look at the status bar! |
| The Code: |
<a href="http://www.mohanjava.com" target='_blank' onMouseover="window.status='World Attractions on your desktop!'; return true" onMouseout="window.status=' '; return true">Place your mouse here and look at the status bar!</a> |
|
|
| Example: Browser forward and backward history move. |
| Note: Will work only if you have any forward or backward history. |
| The Code: |
<form> <input type="button" name="b4" value="back" onClick="history.back()"> <input type="button" name="b5" value="forward" onClick="history.forward()"> </form> |
| Also like: "history.go(-1)" , "history.go(1)", or "history.go(<number of pages to go back/forward>)" |
|
|
| Example: Alert or Message Box. |
| Say Hello |
| The Code: |
<form>
<a href="#" onClick="alert('Hello'); return false;">Say Hello</a>
</br>
<input type="button" name="b6" value="Click here" onClick="alert('If a train station is where the train stops, what is a workstation...?!')">
</form>
|
|
|
| Example: Getting value from a text box. |
| The Code: |
<form name="myForm">
<input type="text" name="tx1" value="">
<input type="button" name="b7" value="Click here" onClick="alert(document.myForm.tx1.value)">
</form>
The syntax is: document.<form name>.<element name>.value
|
|
|
| Example: Asking confirmation from the user. |
| The Code: |
<head>
<script language="javascript">
function makeConfirm() {
var myAnswer = confirm("Now I am going to format your entire harddisk. Is it OK?");
if (myAnswer == true) {
alert("OK. Time to format the harddisk!");
} else {
alert("Sorry. You missed a good chance!");
}
}
</script>
</head>
<body>
<form name="myForm">
<input type="button" name="b8" value="Click here" onClick="javascript:makeConfirm()">
</form>
|
|
|
| Example: Get input from user. |
| The Code: |
<head>
<script language="javascript">
function askName() {
var userName= prompt('Please enter your name, so you can get a special greeting', '');
if (userName == null) {
return;
}
var guest = '';
if ((userName == '') || (userName.length == 0)) {
guest = "Sorry, you didn't enter any name. I treat you as Guest.";
userName = "Guest";
}
alert(guest + "Hello " + userName + ", Welcome to My Page!");
}
</script>
</head>
<body>
<form name="myForm">
<input type="button" name="b9" value="Ask Name" onClick="javascript:askName();">
</form>
</body> |
|
|
| Example: Show current date and time. |
| The Code: |
<form name="myForm">
<input type="button" name="b10" value="Show Date" onClick="javascript:alert(new Date())">
</form> |
|
|
| Example: Openning new window with some options. |
1. To open a new window with the given width, height, no location, no menu bar, no scroll bar, no status bar. Open new window |
2. To open a new window with the given width, height, location, menu bar, scroll bar, status bar. Open new window 2 |
| The Code: |
1. To open a new window with the given width, height, no location, no menu bar, no scroll bar, no status bar.
<A HREF="#"
onClick="window.open
('http://www.world-attractions.com',
'win1',
'width=500,height=400'); return false;">Open new window</a>
. To open a new window with the given width, height, location, menu bar, scroll bar, status bar.
<A HREF="#"
onClick="window.open
('http://www.mohanjava.com',
'win2',
'width=300,height=200,status=yes,menubar=yes,location=yes,scrollbars=yes,resizeable=yes');
return false;">Open new window 2</a>
|
|
|
| Example: Event handling (onClick) |
|
| The Code: |
<IMG name="coolfan" src="fanoff.gif" width="61" height="72"> <input type="button" value=" Off " onClick="coolfan.src='fanoff.gif'"> <input type="button" value=" On " onClick="coolfan.src='fan.gif'"> |
| Example: Event handling (onMouseOver) |
|
| The Code: |
<A href="http://www.world-attractions.com/" onMouseOver="imgfan.src='images/fan.gif'" onMouseOut="imgfan.src='images/fanoff.gif'" target="_blank" ><IMG name="imgfan" src="images/fanoff.gif" width="61" height="72" border="0"></A> |
|
|
| Example: Event handling (onClick and onMouseOver) |
| Click Me to change the window title. (Look at the window title) |
| Move your mouse to change window title |
| The Code: |
<a href="#" onClick="document.title='New title by mouse click'; return false;"> Click Me to change the window title.</a> <a onMouseOver="document.title='New title by mouse over'; return false;"> Move your mouse to change window title</a> |
|
|
| Example: Set focus on a particular form field. |
| User Name : |
| Password : |
| The Code: |
<body> <form name="myForm"> User Name : <input type="text" name="username"> Password : <input type="password" name="password"> <input type="button" value="Set focus on password field" onClick="document.myForm.password.focus()"> </form> |
If suppose want to set the focus at the time of the page loading,
<body onload="document.myForm.username.focus()"> |
|
|
| Example: Characters or string manipulation. |
| Type something (with capital letters): |
| The Code: |
<input type="text" name="textbox1" size="30"> <input type="button" value="Convert to lowercase" onClick="document.myForm.textbox1.value=document.myForm.textbox1.value.toLowerCase();"> |
|
|
| Example: Number of Characters entered. |
| The Code: |
<head>
<script language="javascript">
<!--
function setCount(obj1, obj2) {
obj2.value = obj1.value.length;
}
// -->
</script>
</head>
<body>
<form name="myForm">
<TEXTAREA name="tarea" rows="10" cols="30" value=""
onKeyPress="javascript:setCount(document.myForm.tarea, document.myForm.count);"
onKeyUp="javascript:setCount(document.myForm.tarea, document.myForm.count);"
onKeyDown="javascript:setCount(document.myForm.tarea, document.myForm.count);"></TEXTAREA>
<input type="text" size="3" name="count">
</form> |
|
|
| Example: Event handling - onChange. |
| The Code: |
function openWindow(selectedIndex) {
if (selectedIndex == 'Please Select...') {
return;
} else {
window.open(selectedIndex);
}
}
<select name="jump" OnChange="openWindow(myForm.jump.options[selectedIndex].value)">
<option selected>Please Select...
<option value="http://www.world-attractions.com/">world-attractions.com
<option value="http://www.mtxis.net/">mtxis.net
<option value="http://www.hindumarriage.net/">hindumarriage.net
</select> |
| The "window.open(<url>)" will open a new window with this url. But "location.href=<url>" will open this url in the same window. |
|
|
| Example: While Loop Demo |
| The Code: |
<script language="JavaScript">
<!--- hide script from old browsers
function whileLoopdemo() {
var askAgain = true;
while (askAgain) {
answer = prompt("What is the answer for (10 + 5 - 10) ?", 0);
if (answer.length == 0) {
askAgain = false;
} else if (answer == 5) {
alert("Correct. The Answer is 5.");
askAgain = false;
} else {
askAgain = confirm("Wrong Answer. Want to try again?");
}
}
}
// stop hiding --->
</script><input type="button" value="While Loop Demo"
onClick="whileLoopdemo();"> |
|
|
| Example: Getting selected value from radio button. |
| Male Female |
| The Code: |
<script language="JavaScript">
<!--- hide script from old browsers
function getRadioButtonValue(obj) {
for (i = 0; i < obj.length; i++) {
if (obj[i].checked) {
alert("You are selected " + obj[i].value);
}
}
}
// stop hiding --->
</script>
<input type="radio" name="radio1" value="Male" onClick="javascript:getRadioButtonValue(document.myForm.radio1);">Male
<input type="radio" name="radio1" value="Female" onClick="javascript:getRadioButtonValue(document.myForm.radio1);">Female
|
|
|
| Example: Getting selected values from radio button. |
| Maths English Science History |
| The Code: |
<script language="JavaScript">
<!--- hide script from old browsers
function getCheckBoxValue(obj) {
var message = '';
for (i = 0; i < obj.length; i++) {
if (obj[i].checked) {
message += obj[i].value + ', ';
}
}
if (message == '') {
message = 'No checkbox selected!';
}
alert (message);
}
// stop hiding --->
</script>
<input type="checkbox" name="check1" value="Maths">Maths
<input type="checkbox" name="check1" value="English">English
<input type="checkbox" name="check1" value="Science">Science
<input type="checkbox" name="check1" value="History">History
<input type="button"
value="Get the selected values"
onClick="javascript:getCheckBoxValue(document.myForm.check1);">
|
|
|
| Example: Simple Email id validation. |
|
Enter your email : |
| The Code: |
<script language="JavaScript">
function validateMailId(str) {
var errorMsg = 'Invalid mail id';
var strLength = str.length
if ((str == '') || (strLength == 0)) {
alert(errorMsg);
} else if ((str.indexOf("@") == -1) || (str.indexOf("@") == 0) || (str.indexOf("@") == (strLength - 1))) {
alert(errorMsg);
} else if ((str.indexOf(".") == -1) || (str.indexOf(".") == 0) || (str.indexOf(".") == (strLength - 1))) {
alert(errorMsg);
} else {
alert("May be a valid email id");
}
}
</script>
Enter your email : <input type="text" name="email">
<input type="button" value="Validate Email" onClick="validateMailId(document.myForm.email.value);"> |
|
|
| Example: Form fields validation. |
| * Must fields |
| * User Id : |
| * Password : |
| Email Id : |
| The Code: |
<script language="javascript">
function validateForm() {
var str = document.myForm.uId.value;
if ((str == '') || (str.length == 0)) {
alert ("Please enter User Id");
document.myForm.uId.focus();
return;
}
str = document.myForm.pass.value;
if ((str == '') || (str.length == 0)) {
alert ("Please enter Password");
document.myForm.pass.focus();
return;
}
alert ("Entries OK");
}
</script>
<tr><td>* Must fields</td></tr>
<tr><td>* User Id : <input type="text" name="uId"></td></tr>
<tr><td>* Password : <input type="password" name="pass"></td></tr>
<tr><td>Email Id : <input type="text" name="emailId"></td></tr>
<tr><td><input type="button" value="Validate Form" onClick="validateForm();"></td></tr>
|
|
|