JavaScript Message Box

Background

Many times, I have observed that users put their problem on CodeProject forum related to JavaScript. Really, they don't know 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 easy functions that you can copy and paste it in your code. This resource is entirely about JavaScript.

Introduction

JavaScript is the most popular scripting language and used in almost all browsers. The primary use of JavaScript is to validate user input. Besides that, JavaScript can be used for designing CSS, data manipulation and many more.

Including JavaScript to Page

JavaScript can be used with HTML, DHTML, XML, XHTML, ASP, JSP, ASPX, PHP, etc. JavaScript is defined in a separate block of HEAD. Let's see the following example, it will give you a clear 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 the above code:

  • JavaScript defined under HEAD tag
  • We can write functions in JavaScript
  • function is a reserved keyword
  • 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 cannot change the 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 am just giving an example through functions, you can call them in your page]:

function ValidateME()
{    
if (document.getElementById("txtUserName").value == "")
{
alert("Please enter user Id rraannaammeett");  // 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 document 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 UPs

Most famous part of JavaScript which prompt user from client side. Let's see how can we generate POP UPs 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 a small example:

function askFor()
{	
if (confirm("Are you sure rraannaammeett"))
alert("Yes, i am sure rraannaammeett")
else alert("No, i am not sure rraannaammeett")
}

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 supports a number 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 example 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 rraannaammeett!">Over Here!</a> <a href="#" onMouseOut="alert('Hin I am mouse out !')">Get Out Here!</a> </body> 

onUnLoad

This event calls JavaScript function while someone leaves the page, e.g., Giving thanks message when user leaving page:

<body onunload="alert('Thank you for visiting rraannaammeett')">

onblur

This event call when any user leaves Textbox, it is same like a LostFocus event in Winforms. 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 work with date in JavaScript. Here are some good examples to display today's 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 functions that deal 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)

Functions That Make Life Easy

Let's rock with the following functions that make life easy.
You 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 rraannaammeett");
    }

    *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: evaluates the expression and gets 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 rraannaammeett!");
    }

    *\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

    The following code is 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 specified char.

  8. Validate EMail address

    The following code is used to validate email address with Regular expression:

    function ValidateEmail()
    {	
    var pattern = "/^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/";
    str = "[email protected]";
    alert(str.match(pattern));
    return false;
    }
  9. Showing/Hiding controls on specific condition

    Lot of times, we need to Hide / show a control against a specific condition. Here is the function, which will help us to TOGGLE the view state just pass the control id to the 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;
    }
  11. 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 the above function on OnCLIENTCLICK event
    * for document, call the above function on ONCLICK event of BODY

  12. 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 enabled for script in Internet Explorer. To check setting, go to
    Internet Explorer --> Tools --> Internet Options --> Advanced Tab

    Debugger Setting

Ebook Download
View all
Learn
View all