Javascript : A Quick Check
Background
Many Times i have observed, user put their problem on CP forum related to Javascript.
Really they don't know what the exact use of Javascript. Why we should use it ?
Where to define it?
In this article i will explain what is javascript, why Javascript is used, How to use Javascript for validation,
use of functions and properties and some life make easy functions that you can copy and paste it in your code.
This resource is whole about Javascript.
Introduction
Javascript is Most popular scripting language and used in almost all browsers. The primary use of Javascript is to Validate user input. Beside that, Javascript can be used for Designing CSS, Data manupulation and many more.
Including Javascript to Page
Javascript can be used with HTML, DHTML, XML, XHTML, ASP, JSP, ASPX, PHP etc. Javascript defined in a separate block of HEAD. let's see the following example, it will clear your idea.
<html> <head> <script language="JavaScript"> function CallMe() { alert("Yes..first POP up from javascript"); return false; } </script> </head> <body> Welcome to javascript example! <input type="submit" id="sub1" onclick="return CallMe();"> </body> </html>
let's Travel with above code
-
- Javascript defined under HEAD tag
- We can write functions in javascript
- function is reserved keywords
- alert is used for POP message
- return false indicates page should not submit to server (means code execution will stop at that point)
- We can call javascript function using onclick event
- Like VBScript we can not change caption of POPup box in javascript
using document object
document is Most common used object in javascript. Using document object we can collect any control from page. Let's take an example.Validating Page for empty textbox using document object [now i just giving example through functions, you can call them in your page]
function ValidateME() { if (document.getElementById("txtUserName").value == "") { alert("Please enter user id"); // Give alert to user document.getElementById("txtUserName").focus(); // Set focus on textbox return false; } }Change forecolor / Backcolor of page using document object
function ChangeME() { document.bgColor="red"; //change the backcolor to RED document.fgColor="#338844"; //change the forecolor }Write on a page using doument object
function WriteME() { document.write ("I can write on page"); }Access form controls using 'ALL' property (ALL property is browser(IE) specific)
function GetControlValue() { alert(document.all.txtUser.Value); }document object has a Numerous functions and properties here are some of them.
-
- alinkColor - Specifies the color of activated links
- domain - Gives domain name under which served you used for security purpose
- title - Specifies the title of document
- cookie - A string containing the name/value pair of cookies in the document.
- FileSize - Return the file size of the current document
- URL - A string that specifies the complete URL of the document.
- cookie - A string containing the name/value pair of cookies in the document
POP UP's
Most famous part of Javascript, Which prompt user from client side. Let's see how can we generate POP UP's with some lines of code.using alert
ALERT can be used to alert the user. A simple messagebox accepted by all browsers.
here is small example
function giveAlert() { alert("WOW ! this is alert"); return false; }using confirm
CONFIRM can be used to confirm user decision. a simple messagebox with OK and CANCEL buttons. This function returns boolean value.
here is small example
function askFor() { if (confirm("Are you sure")) alert("Yes, i am sure") else alert("No, i am not sure") }using Prompt
This is used to accept input from user
function EnterChoice() { var reply = prompt("what is your name","Enter your name") alert("HI" + reply); }here var is the datatype in javascript like integer, string and "reply" is the variable.
Event Handling
Javascript support numbers of events, here we go for some most common/used events.
onClick -
This event is mostly supported by all controls of webform.
onClick handlers execute something only when users click on buttons, links, checkbox, radiobutton etc.
<script> function callME() { alert("yes..OnClick called!") } </script> <form> <input type="button" value="Click Me" onclick="callME()"> </form>onchange -
This event fired by combo box while changing items in combo list. Here is the exaple of how to get an selected item from dropdownlist
<script> function getItem() { alert("you select " + document.getElementById("idDDL").value) } </script> <form> <asp:Dropdownlist id="idDDL" runat="server" onchange="getItem()"> <listItem>a<listItem> </asp:Dropdownlist> </form>onMouseover,onMouseout -
These are exclusive events used when mouse pointer OVER and OUT from control.
<body> <a href="#" onMouseOver="alert('Hi,I am mouse over!">Over Here!</a> <a href="#" onMouseOut="alert('Hin I am mouse out !')">Get Out Here!</a> </body>onUnLoad -
This event call JavaScript function while someone leaves the page, e.g Giving thanks message when user leaving page
<body onunload="alert('Thank you for visiting')">onblur -
This event call when any user leaves Textbox, it is same like a LostFocus event in win forms. e.g. we can validate if user has left textbox empty
function ValidateInt() { if (document.getElementById("txtNum").value == "") { alert("You can not left number field empty"); document.getElementById("txtNum").focus(); return false; } }
Working with dates
very few developers has work with date in javascript,here are some good example Display todays date.<HTML> <HEAD> <TITLE>Date using Javascript</TITLE> </HEAD> <BODY> <SCRIPT LANGUAGE="JavaScript"> function CallMe() { var dt= new Date(); alert ("Todays date is " + dt); } </SCRIPT> </BODY> </HTML>Here are some function that deals with date object
-
- getTime() - Get Number of milliseconds
- getSeconds() - Get Number of seconds (0-59)
- getMinutes() - Get Number of minutes (0-59)
- getMinutes() - Get Number of minutes (0-59)
- getHours() - Get Number of hours (0-23)
- getDay() - Get Day of the week(0-6). 0 = Sunday, ... , 6 = Saturday
- getDate() - Get Day of the month (0-31)
- getMonth() - Get Number of month (0-11)
- getFullYear() - Get year range between(1970-9999)
LIFE MAKES EASY FUNCTIONS
Let's rock with the following life make easy functionsYou can call these functions on any event in your web application like onclick, onblur, onchange etc.
1. Check if the Textbox has numeric value
function checkInt() { if (isNAN(document.getElementById("txtNum").value)) alert("Please enter only numbers"); }*isNAN : The NaN property represents "Not-a-Number" value. This method indicates that a value is not a legal number.
2. evaluate expression
function checkInt() { function evaluateME() { alert(eval(2+2)); } }*eval : evaluate the expression and get the output
3. Display only specified length of string
function FormatMe() { var exNum = new Number(3.141516254); alert(exNum.toPrecision(4)); } //Output : 3.141*toPrecision() :This method formats a number to a specified length.
4. Alert box with line break
Many times we need to display message on different lines, here we go.
function disp_alert() { alert("This is line 1 " + '\n' + "Yes, I am after line break!"); }*\n :Used to break lines.
5. Get how many char's enter in textbox
function disp_char() { alert("You have entered " + document.getElementById("txtUser").length() + " chars); }*length() :Used to get the length of textbox.
6. Case Insensitive String Compare
function ValidateCases() { var user1 = document.getElementById("txtUser").value; if(user1.toLowerCase() == "Welcome".toLowerCase()) alert("Welcome matched"); else alert("Access Denied!"); }*toLowerCase() :Convert string to lower case.
7. Split string with javascript
following code used to split string values with specified split char
function SplitME() { var myString = "str1/str2"; var mySplitResult = myString.split("/"); alert("The first element is " + mySplitResult[0]); alert("The second element is " + mySplitResult[1]); }*split() :This method is used to split the string with spcified char
8. Validate EMail address
following code used to validate email address with Regular expression
function ValidateEmail() { var pattern = "/^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/"; str = "test@gmail.com"; alert(str.match(pattern)); return false; }9. Showing/Hidding controls on specific condition
Lot of time we need to Hide / show a conrtol against a specific condition. here is the function, which will help us to TOGGLE the view state just pass the control id to following function
function Toggle(obj) { var ctrlid = document.getElementById(obj); if ( ctrlid.style.display != 'none' ) ctrlid.style.display = 'none'; else ctrlid.style.display = ''; }10. Prevent ENTER key on Textbox
call the following function on keypress event of Textbox.
function avoidEnter() { if (event.keyCode == 13) return false; }10. Disabled RIGHT click using Javascript
If you need to disabled right click on Textbox / Document use the following function
function DisableRight() { if (event.button == 2) return false; }* for textbox call above function on OnCLIENTCLICK event
* for document call above function on ONCLICK event of BODY
11. Debugging Javascript with Visual studio
You can debug the Javascript functions, just by adding debugger; keyword in function.
but before start debugging, make sure that your debugging is enable for script in Internet Explorer.
To check setting go to
Internet Explorer --> Tools --> Internet Options --> Advanced Tab
Some interesting facts
Here are some interesting facts about javascript you might unaware of it
- The father of JavaScript is Brendan Eich
- Javascript was known as Livescript in early days
- The Current version of Javascript used is 1.8.5 and was put in world in July 27, 2010
This is all about the Javascript : A Quick Check.
Hope it will help you to understand Javascript concept.
Suggestion and feedback most welcome.
Thanks
koolprasad2003
Post Comment
lD4CGi I value the article post.Much thanks again. Great.
xNScdP Really informative post.Really thank you! Keep writing.