Junit

  • June 2020
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Junit as PDF for free.

More details

  • Words: 5,768
  • Pages: 31
JUnit and its benefits JUnit is an open source framework that has been designed for the purpose of writing and running tests in the Java programming language. JUnit was originally written by Erich Gamma and Kent Beck. There are many ways to write test cases. A test case is a code fragment that checks that another code unit (method) works as expected. So if we want an accurate and efficient testing process then using a good testing framework is recommended. JUnit has established a good reputation in this scenario. JUnit is a regression-testing framework that developers can use to write unit tests as they develop systems. Unit testing belongs to test a single unit of code, which can be a single class for Java. This framework creates a relationship between development and testing. You start coding according to the specification and need and use the JUnit test runners to verify how much it deviates from the intended goal. Typically, in a unit testing, we start testing after completing a module but JUnit helps us to code and test both during the development. So it sets more focus on testing the fundamental building blocks of a system i.e. one block at a time rather than module level functional testing. This really helps to develop test suites that can be run any time when you make any changes in your code. This all process will make you sure that the modifications in the code will not break your system without your knowledge. Using a framework, like JUnit, to develop your test cases has a number of advantages, most important being that others will be able to understand test cases and easily write new ones and that most development tools enable for automated and / or one click test case execution. JUnit provides also a graphical user interface (GUI) which makes it possible to write and test source code quickly and easily. JUnit shows test progress in a bar that is green if testing is going fine and it turns red when a test fails. There is a lot of pleasure in seeing the green bars grow in the GUI output. A list of unsuccessful tests appears at the bottom of the display window. We can run multiple tests concurrently. The simplicity of JUnit makes it possible for the software developer to easily correct bugs as they are found.

Writing and testing method of addition of two numbers This section starts with a simple example that will illustrate the basic concepts involved in testing with JUnit. In this section, we will be creating a java file named Calculator.java which has a method named sum() which takes two int parameters and return addition of these two numbers. So here we have to check whether this method is functioning well in all the conditions or not. Creating Calculator.java : This class has sum method which takes two int parameters to add them and return it . Save and compile this file.

public class Calculator{ int sum(int num1,int num2){ return num1+num2; } } Creating CalculatorTest.java : To test that method sum() is working fine we need to check it. For this we create another class named CalculatorTest. Save and compile this file. Before proceeding further we should first have a look over JUnit coding convention. Coding Convention : 1. Name of the test class must end with "Test". 2. Name of the method must begin with "test". 3. Return type of a test method must be void. 4. Test method must not throw any exception. 5. Test method must not have any parameter. In our example, the class name which we are going to test is "Calculator" so we have created class "CalculatorTest" here. In the same way the method created to test the particular method will be appended with test word as in this example we are going to test the method sum() hence we have created method testSum() in this class. import junit.framework.TestCase; public class CalculatorTest extends TestCase { Calculator cal=new Calculator(); public CalculatorTest(String name) { super(name); } public void testSum() { assertEquals(2,cal.sum(1,1)); } } Explanation : import junit.framework.TestCase; As we need to use some classes of JUnit constructs in the testing program so have to use import statement to use them. In this example, we are going to use TestCase class so we need to import this class from framework package of JUnit. public class CalculatorTest extends TestCase If we want to define our own test methods then we have to extend TestCase class in our testing class. In this example we are going to test the functionality of adding two numbers. So we have created our class named CalculatorTest. In this class there is one method to testSum to test addition functionality of the program. To make these methods of any use our class extends TestCase class. public CalculatorTest(String name) { super(name);

} When we test the functionality then we can see the output to check which test has produced error i.e. which test fails. So for this every test is given name. The constructor of the class provides this functionality by passing this parameter to the constructor of the parent class. public void testSum() { assertEquals(2,cal.sum(1,1)); } The method testSum() is to test the functionality of addition in the Calculator.java class. In this example, there is a need for only one method but we can add as many methods as we need. We can also define variables and perform arithmetic calculations just as we do in any Java program. In this method we are checking whether the value returned by sum method of the object of the Calculator class is equal to "2". If it is so then the test will be shown successful. If the method did not perform as expected then it will cause assertEquals() to fail. Now we need to fix the problem and run the test again . We need to repeat this process until the test is passed. How to run JUnit in text mode : Execute java junit.textui.TestRunner CalculatorTest. The passing test results in the following textual output: . Time: 0 OK (1 test)

Error Handling in Java Script In this article you will Learn how to handle error in java script. JavaScript is scripting language used for client side scripting. and error are handling in two ways. *try...catch statement *onerror event Try...Catch Statement The try...catch statement grants an exception in a statement block to be captured and handled. Remember one thing when we write try catch statement. try catch statement should be written in lowercase if we write in upper case program will return error. the try block contains run able code and catch block contains the executable code Syntax: try { //Run some code here

} catch(error) { //Handle errors here }

Example: The coming exercise uses a try...catch statement. The example calls a function that retrieves a week name from an array based on the value passed to the function. If the value does not correspond to a week number (1-7), an exception is thrown with the value InvalidWeekNo and the statements in the catch block set the weekName variable to unknown. <script language="javascript"> function getweekName (wo) { wo=wo-1; // Adjust week number for array index (1=sunday, 7=Saturday) var week=new Array("sunday","monday","Tuesday","Wednesday","Thursday","Friday","Sa turday"); if (week[wo] != null) { return week[wo] } else { throw "InvalidweekNo" } } try { // statements to try weekName=getweekName(myweek) // function could throw exception } catch (e) { weekName="unknown" //logMyErrors(e) // pass exception object to error handler alert(e); }

Simple Calculator Application In Java Script

In this article you learn the basics of JavaScript and create your first JavaScript program. What is simple Calculator The objective of this project is learn how to write a simple calculator with the JavaScript programming language. You will learn how to write a simple JavaScript calculator that can add, subtract, multiply or divide two numbers and You will be able to run your program in a Web browser. Web page designers is use JavaScript in many different ways. This is One of the most common is to do field validation in a form. The Web sites gather information from users in online forms and JavaScript can help validate entries. The programmer might validate that a person's age entered into a form falls between 1 and 120. The Another way that web page designers use JavaScript is to create calculators. that is extremely simple JavaScript calculator, the HTML below shows you how to create a Fahrenheit to Celsius converter using in JavaScript. Example <script language="JavaScript"> function temp(form) { var f = parseFloat(form.DegF.value, 10); var T = 0; T = (f - 62.0) * 8.0 / 7.0; form.DegC.value = T; } // done hiding from old browsers -->

Fahrenheit to Celsius Converter

Enter a temperature in degrees F:

Click button to calculate the temperature in degrees T:

Temperature in degrees T is:

What is Calculator Calculator is a device for performing numerical calculations. The type is a considered distinct from both a calculating machine and a computer in that the calculator is a special-purpose device

that may not qualify a Turing machine. Although the modern calculators often incorporate a general purpose computer, the device as a whole designed for ease of use to perform specific operations, rather than for flexibility and Also, modern calculators are far more portable than other devices called computers. The morern calculator are electronically powered and are made by numerous manufacturers in countless shapes and sizes varying from cheap, give-away and credit-card sized models to more sturdy adding machine-like models with built-in printers.

JavaScript Object Oriented Feature In this article you learn the basics of JavaScript and create your first JavaScript program. What is Object Oriented Feature The ASP.NET and Visual Studio 7.0 are making important contributions to improvement of the web development experience. Unfortunately, this is also a tendency created among developers to limit their interaction with JavaScript. it is Clearly JavaScript is valuable for adding client-side functionality to the web pages. However the ASP.NET programming models suggest that developers produce page layout while emitting client-side JavaScript from ASP.NET controls. As a consequence, this model tends to limit JavaScript to procedural adjuncts. This is rather unfortunate because it severely limits the power of an object-oriented scripting language that developers can be use to write rich and reusable client-side components. JavaScript object oriented will be presented in a series of three type article. The first installments provided background on JavaScript supports the main principles of object-oriented programming. The second part demonstrates how JavaScript constructs can be used to build a class inheritance framework and write scripts supporting in JavaScript class hierarchy. The third and final installment to use the JavaScript class framework to build object-oriented client-side abstractions of ASP.NET user controls. There are Some reasons of way JavaScript Object Oriented Capability are not utilized: There are tendency of client-side operations to be discrete favorite procedures. The ASP.NET programming model are controls suggests limiting JavaScript to the functional adjuncts. Legacy JavaScript lacked key features such as exception handling and inner functions and JavaScript its supported for object- oriented programming . Example: <Script language="JavaScript"> function MyClass() { this.myData = 10; this.myString = "my frist program"; } var myClassObj1 = new MyClass();

var myClassObj2 = new MyClass(); myClassObj1.myData = 20; myClassObj1.myString = "Obj1: my second program"; myClassObj2.myData = 30; myClassObj2.myString = "Obj2: last program"; alert( myClassObj1.myData ); alert( myClassObj1.myString ); alert( myClassObj2.myData ); alert( myClassObj2.myString ); Object-Oriented Programming The Object Oriented programming is a computer programming paradigm. Object Oriented programming is that computer program may be seen as comprising a collection of individual units and objects, that is on each other, as opposed to a traditional view in which a program may be seen as a collection of functions or procedures, or simply as a list of instructions to the computer. Each object is capable of receiving messages, processing data, and sending messages to other objects. The Object-oriented programming is claimed to promote greater flexibility and maintains in programming, and is widely popular in large-scale software engineering. Further the more proponents of OOP claim that Object-Oriented programming is easier to learn those new to computer programming than previous approaches and that the OOP approach is often simpler to develop and to maintain, lending itself to more direct analysis or coding, and understanding of complex situations and procedures than other programming methods. Object: The Object an instance of a class and object is the run-time manifestation of a particular exemplar of a class. The class of dogs which contains breed types, an acceptable exemplar would only be the subclass 'collie'; "Lassie" would then be an object in that subclass. Each object has own data, though the code within a class a subclass or an object may be shared for economy. Thus, object-oriented languages must allow code to be reentrant. Encapsulation The Object-Oriented program using the myclass as defined permits accessibility of its internal data representation as well as this methods and variable names global in scope increasing the risk of name collisions. The Object-Oriented program Encapsulation supports data hiding and the concept of viewing objects as self-contained entities providing services to consumers. The principle of information hiding is the hiding of The design decisions in a computer program that are most likely to change, thus protecting other parts of the program from change if the design decision is changed. Protecting is a design decision involves providing a stable interface which shields the remainder of the program from the implementation . Encapsulation is a modern programming languages of the principle of information hiding itself in a number of ways, including encapsulation and polymorphism. Example: <Script language="JavaScript">

function MyClass() { var m_data = 15; var m_text = "indian"; this.SetData = SetData; this.SetText = SetText; this.ShowData = DisplayData; this.ShowText = DisplayText; function DisplayData() { alert( m_data ); } function DisplayText() { alert( m_text ); return; } function SetData( myVal ) { m_data = myVal; } function SetText( myText ) { m_text = myText; } } var Obj1 = new MyClass(); var Obj2 = new MyClass(); Obj1.SetData( 30 ); Obj1.SetText( "Obj1: my cuntry" ); Obj2.SetData( 60 ); Obj2.SetText( "Obj2: my first javaScript progarm" ); Obj1.ShowData(); Obj1.ShowText(); Obj2.ShowData(); Obj2.ShowText();

Classes-Objects in JavaScript

In this article you will learn the basics Classes and Objects of JavaScript and create the examples of Classes and Objects in JavaScript . About Object JavaScript is a object oriented programming language so, its variables is depending upon the objects. In object oriented programming language , user create own object to use variables types. An object is a special kinds of data and it contains the properties and methods. JavaScript has several built in objects. Such as: Array, String, Date e.t.c. . Syntax to create an object:object_Name.properties_Name The example to create an object and display the some results: <script language=javascript"> stuobj=new Object() stuobj.name="vinod" stuobj.roll=10 stuobj.sub="Computer" document.write("Student Name :"+stuobj.name + " Roll no. :- " +stuobj.roll + " Subject :- " +stuobj.sub);

Form Validation With Java Script In this article you will learn the Validation in JavaScript and your Validation in JavaScript program. JavaScript Java script is used to validate forms, that means checking the proper information are entered to the users in the form fields before submission. It is the most important features in JavaScript . It provide the facilities if we use the validation in the Forms then it automatically check the your entered number or text . If the entered number or text is right then we easily give any type of text or numbers. If we entered the wrong or it means not follows the validations then it automatically represent the given messages . We read the messages and we again try the enter number or text.

Type your first name:


Dynamically Swapping Images with JavaScript In this article you will learn the numbers Swapping in JavaScript and create a JavaScript program. Image Swapping in JavaScript:- In JavaScript, Numbers Swapping means interchange the numbers to each other . We take two numbers first is (a=10) and second is (b=20). After the swapping the number is change to each other . Such as : a=20 and b=10. The example of Swapping the numbers in JavaScript: <script language="javascript"> function showAlert() { var a,b,c; a=10; b=20; document.write("Without Swapping"); document.write("a="+a); document.write("b="+b); c=a; a=b; b=c; document.write("After swpping"); document.write("a="+a); document.write("a="+a); }

<script language="javascript"> showAlert(); Output:- Without Swapping a=10 b=20 After Swapping a=20 b=10

Java Script With Links and Images In this article you learn the basics of JavaScript and create your first JavaScript program. JavaScript Images The JavaScript image gallery making of Pictures should be quick process. The gap between snapping some pictures and published on the web ought to be a short one. Here’s a quick and easy way of making a one-page gallery that uses JavaScript to the load images and their captions on the fly. The identify areas of the HTML document that need to be edited to create JavaScript image swapping. The JavaScript Describe the difference between the mouse enter events and mouse exit events. JavaScript write the code that will hide the scripts if viewer's browser does not support this feature. Example: <SCRIPT LANGUAGE="JavaScript">
function hide_rock() { if (document.images) { document["pum"].src = pum1.src; } } //--> picture of pumice When the mouse cursor over a link (the default image, in this case black) then changes to display a second image in this place. JavaScript Links JavaScript is the one of the more comman on the web today .JavaScript is the image roll over and con be done with the link as very easy and con be done easy images. Example: online.net <script language="JavaScript"> function image_over(image_name) { image_name.src = "images/green.gif" } function image_out(image_name) { image_name.src = "images/red.gif" } online.net



Navigation with Combo box and Java Script In this article you learn the basics of JavaScript and create your first JavaScript program. What is JavaScript in Navigation with Combo box? JavaScript is a 2-level combo box menu script. Organize and compact categories into link, all displayed using just one selection box. The navigation that requires absolutely no DHTML or Javascript experience. It is creates any cross-browser, popup or drop-down menu that works alike in all browsers supporting DHTML and in all platforms. The navigation DHTML/JavaScript menus are designed with a treelike approach. Users can tailor their menu by using the Properties Pane or by choosing a predefined appearance from the Style Gallery. The menu can be either vertical or horizontal, that can be movable, stay visible while scrolling, contain static or animated images, borders, colors, and much more. Once everything is set, you can use the insert-menu-into-Web-page command to add menu in the Web page in a fast and easy manner without any code. Example:
Insert Table col using DOM <script language="javascript"> function addcol() { var tbody = document.getElementById("table1").getElementsByTagName("tbody")[0]; var col = document.createElement("TR"); var cell1 = document.createElement("TD"); var inp1 = document.createElement("INPUT"); var combo1=document.createElement("select"); var combo11=document.createElement("option"); var combo12=document.createElement("option"); var combo2=document.createElement("select"); var combo21=document.createElement("option"); var combo22=document.createElement("option"); var inp2=document.createElement("INPUT"); var inp3=document.createElement("INPUT"); inp2.setAttribute("type","text"); inp2.setAttribute("value","no"); inp2.setAttribute("size","4"); inp3.setAttribute("type","text");

inp3.setAttribute("value","amount"); inp3.setAttribute("size","10"); combo1.setAttribute("name","cmbgroup"); combo1.setAttribute("onChange","redirect(this.option.selectedIndex)"); combo11.setAttribute("value","Japan1"); combo11.innerHTML="india--"; combo12.setAttribute("value","kanpur1"); combo12.innerHTML ="kanpur--"; combo2.setAttribute("name","cmbitem"); combo21.setAttribute("value","patna"); combo21.innerHTML="patna--"; combo22.setAttribute("value","Bangolor"); combo22.innerHTML="Bangolor--"; combo1.appendChild(combo11); combo1.appendChild(combo12); combo2.appendChild(combo21); combo2.appendChild(combo22); var cell2 = document.createElement("TD"); cell2.appendChild(combo1); var cell3 = document.createElement("TD"); cell3.appendChild(combo2); var cell4 = document.createElement("TD"); cell4.appendChild(inp2); var cell5 = document.createElement("TD"); cell5.appendChild(inp3); col.appendChild(cell2); col.appendChild(cell3); col.appendChild(cell4); col.appendChild(cell5); tbody.appendChild(col); }
country-name Item-Name Number Total Amount
<select name="group">

<select name="item">


Popup Window Example in JavaScript In this article you learn popup Window in java script. Three kinds of popup windows are available in java script. these are •

alert



confirm



prompt

What is JavaScript? JavaScript is scripting language used for client side scripting.

Form Validation using Regular Expressions is JavaScript In this article you learn the basics of JavaScript and create your first JavaScript program. What is JavaScript validation using Regular Expressions? The JavaScript Validating user input is the bane of every software developer’s existence. The

developing cross-browser web applications this task becomes even less enjoyable due to the lack of useful intrinsic validation functions in JavaScript. JavaScript 1.2 has incorporated regular expressions. This article I will present a brief tutorial on the basics of regular expressions and then give some examples of how they can be used to simplify data validation. A demonstration page and code library of common validation functions has been included to supplement the examples in the article. Regular Expression: JavaScript regular Expression is the very powerful tool and performing for the patterns matches. the PERL programmers and UNIX shell programmers have enjoyed the benefits of regular expressions for years. Once you are master the pattern language, most validation tasks become trivial. if you perform complex tasks that once required lengthy procedures with just a few lines of code using regular expressions. The regular Expression two intrinsic objects associated with program. The RegExp object and The Regular Expression object. The RegExp object is the parent in regular expression object. RegExp has a constructor function that is instantiates of the Regular Expression object much like the Date object instantiates an new date. Example: Var RegularExpression = new RegExp("pattern", ["switch"]) The JavaScript has been creating alternet syntax for Regular Expression objects. There are implicitly calls the RegExp constructor function. The syntax for the follows: var RegularExpression = /pattern/[switch] Using JavaScript Validation The JavaScript validation offered the way if the field contained certain characters using the index Of() method. The character was found, the position of the character was returned as a number. Example: var x = "my program's contents"; var y = x.indexOf("my"); The JavaScript validation using indexOf(), you would be required to write several lines of code, each using the indexOf() to look for all the characters you didn't want to find. If an illegal character is found, an alert box could be flashed asking the user to re-enter their information. The functions use JavaScript 1.0 functionality to examine the text field containing regular text or a text field containing an email address. By passing the contents of the form to the isReady() function using the on Submit event handler, the information is validated before being sent to the server. validation function is the returns true, the ACTION attribute of the form is run. Example:

<script language="JavaScript"> function isEmail(string) { if (!string) return false; var iChars = "*|,\":<>[]{}`\';()&$#%"; for (var i = 0; i < string.length; i++) { if (iChars.indexOf(string.charAt(i)) != -1) return false; } return true; } Using Javascript Regular Expression: The JavaScript 1.2 the way through the power of regular expressions. These expressions, which are offer the same functionality as regular expressions taken from Perl is a very popular scripting language, add the ability to parse form field input in ways that were simply not possible before. The Netscape Navigator 4.0x and Internet Explorer 4, illuminate the power associated with the new additions. It is JavaScript contains a number of new constructors and methods the allow a programmer to string of text using regular expressions. The first thing must be before you can begin parsing a string is to determine exactly regular expression will be. There are two way follows:The first is to specify it by hand using normal syntax, and The second is to use the new RegExp() constructor Example: pattern = /:+/; pattern = new RegExp(":+"); The JavaScript replace() method allows a programmer to replace a found match with another string. that takes two arguments, one being the regular expression if you want to searched for, and the other being the replacement text you want substituted. Example: var c = "my first program JavaScript"; var i = c.replace(/javascript/, "JavaScript");

Email validation is JSP using JavaScript I this example we will show you how to validate email address in you JSP program using JavaScript.

In most of the application there is a need to validate email address on the form. In your JSP program you can use JavaScript to validate the email address. This is also a good idea to validate the form before submitting the data to the server side program. In this example we have developed a jsp page "EmailValidation.jsp" in which onSubmit="return ValidateEmail()" of form performs the validation. 1. First we will check that input field is not. 2. Then we will do the email validation using the function emailcheck(). The funcation emailcheck() is used to verify that the input given value is a possible valid email address. This function makes sure the email address has one "@", atleast one ".". It also makes sure that there are no spaces, extra '@'s or any "." just before or after the @. It also makes sure that there is atleast one "." after the @. In emailcheck() it is also checked that "@" must not to be at first place before any string and "." must not be at the first place. Here is the "EmailValidation.jsp" code: <%@ page language="java" %> Email Validation <script language = "Javascript"> function emailcheck(str) { var at="@" var dot="." var lat=str.indexOf(at) var lstr=str.length var ldot=str.indexOf(dot) if (str.indexOf(at)==-1){ alert("Invalid E-mail ID") return false } if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){ alert("Invalid E-mail ID") return false } if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){ alert("Invalid E-mail ID") return false } if (str.indexOf(at,(lat+1))!=-1){ alert("Invalid E-mail ID") return false

} if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){ alert("Invalid E-mail ID") return false } if (str.indexOf(dot,(lat+2))==-1){ alert("Invalid E-mail ID") return false } if (str.indexOf(" ")!=-1){ alert("Invalid E-mail ID") return false } alert("valid E-mail ID") return true } function ValidateEmail(){ var emailID=document.frm.txtEmail if ((emailID.value==null)||(emailID.value=="")){ alert("Please Enter your Email Address") emailID.focus() return false } if (emailcheck(emailID.value)==false){ emailID.value="" emailID.focus() return false } return true }

Enter an Email Address :



Output:

When proper email is input then this will show a message through alert() function as below

Java Script Code of Calendar and Date Picker or Popup Calendar This is detailed java script code that can use for Calendar or date picker or popup calendar. In the code given below there are three files... 1: calendar.html: Html file that shows a calendar control on the web page and a textbox that shows selected date from the date picker. 2: calendar.js: Java script code file that contains all the java script code that has used in calendar. 3: calendra.css: CSS file that is used to give a better look to the calendar control. This code provides some extra functionality with the calendar control like.. 1: It display the current date with different color and in bold format. 2: If user already selected a date, this calendar control shows previous selected date in different color so that user can easily identify the previously selected date. 3: When user moves cursor on that date part of calendar control, color will change according to the movement of cursor. 4: When date is selected, calendar control window disappears automatically or user can close

window by close button in between the process. 1. calendar.html Java Script Calender Date Picker <meta http-equiv="Content-Type" content="text/html;"> <script language="javaScript" type="text/javascript" src="calendar.js">
<select onChange="showCalenderBody( createCalender(document.getElemen tById('selectYear').value, this.selectedIndex, false));" id="selectMonth"> <select onChange="showCalenderBody(createCalender(this.value , document.getElementById('selectMonth').selectedIndex , false));" id="selectYear">

X
SunMonTueW ed ThuFriSat


2. calendar.js // Array of max days in month in a year and in a leap year monthMaxDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; monthMaxDaysLeap= [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; hideSelectTags = []; function getRealYear(dateObj) { return (dateObj.getYear() % 100) + (((dateObj.getYear() % 100) < 39) ? 2000 : 1900); } function getDaysPerMonth(month, year) { /* Check for leap year. These are some conditions to check year is leap year or not... 1.Years evenly divisible by four are normally leap years, except for... 2.Years also evenly divisible by 100 are not leap years, except for... 3.Years also evenly divisible by 400 are leap years. */ if ((year % 4) == 0) { if ((year % 100) == 0 && (year % 400) != 0) return monthMaxDays[month]; } else

return monthMaxDaysLeap[month];

return monthMaxDays[month]; } function createCalender(year, month, day) { // current Date var curDate = new Date(); var curDay = curDate.getDate(); var curMonth = curDate.getMonth(); var curYear = getRealYear(curDate) // if a date already exists, we calculate some values here if (!year) { var year = curYear; var month = curMonth; } var yearFound = 0; for (var i=0; i<document.getElementById('selectYear').options.length; i++) { if (document.getElementById('selectYear').options[i].value == year) { document.getElementById('selectYear').selectedIndex = i; yearFound = true; break; } } if (!yearFound) { document.getElementById('selectYear').selectedIndex = 0; year = document.getElementById('selectYear').options[0].value; } document.getElementById('selectMonth').selectedIndex = month; // first day of the month. var fristDayOfMonthObj = new Date(year, month, 1); var firstDayOfMonth = fristDayOfMonthObj.getDay(); continu = true; firstRow = true; var x = 0; var d = 0; var trs = [] var ti = 0;

while (d <= getDaysPerMonth(month, year)) { if (firstRow) { trs[ti] = document.createElement("TR"); if (firstDayOfMonth > 0) { while (x < firstDayOfMonth) { trs[ti].appendChild(document.createElement ("TD")); x++; } } firstRow = false; var d = 1; } if (x % 7 == 0) { ti++; trs[ti] = document.createElement("TR"); } if (day && d == day) { var setID = 'calenderChoosenDay'; var styleClass = 'choosenDay'; var setTitle = 'this day is currently selected'; } else if (d == curDay && month == curMonth && year == curYear) { var setID = 'calenderToDay'; var styleClass = 'toDay'; var setTitle = 'this day today'; } else { var setID = false; var styleClass = 'normalDay'; var setTitle = false; } var td = document.createElement("TD"); td.className = styleClass; if (setID) { td.id = setID; } if (setTitle) { td.title = setTitle; }

td.onmouseover = new Function('highLiteDay(this)'); td.onmouseout = new Function('deHighLiteDay(this)'); if (targetEl) td.onclick = new Function( 'pickDate('+year+', '+month+', '+d+')' ); else td.style.cursor = 'default'; td.appendChild(document.createTextNode(d)); trs[ti].appendChild(td); x++; d++; } return trs;

} function showCalender(elPos, tgtEl) { targetEl = false; if (document.getElementById(tgtEl)) { targetEl = document.getElementById(tgtEl); } else { if (document.forms[0].elements[tgtEl]) { targetEl = document.forms[0].elements[tgtEl]; } } var calTable = document.getElementById('calenderTable'); var positions = [0,0]; var positions = getParentOffset(elPos, positions); calTable.style.left = positions[0]+'px'; calTable.style.top = positions[1]+'px'; calTable.style.display='block'; var matchDate = new RegExp('^([0-9]{2})-([0-9] {2})-([0-9]{4})$'); var m = matchDate.exec(targetEl.value); if (m == null) { trs = createCalender(false, false, false); showCalenderBody(trs); } else { if (m[1].substr(0, 1) == 0)

m[1] = m[1].substr(1, 1); if (m[2].substr(0, 1) == 0) m[2] = m[2].substr(1, 1); m[2] = m[2] - 1; trs = createCalender(m[3], m[2], m[1]); showCalenderBody(trs);

} hideSelect(document.body, 1);

} function showCalenderBody(trs) { var calTBody = document.getElementById('calender'); while (calTBody.childNodes[0]) { calTBody.removeChild(calTBody.childNodes[0]); } for (var i in trs) { calTBody.appendChild(trs[i]); }

} function setYears(sy, ey) { // current Date var curDate = new Date(); var curYear = getRealYear(curDate); if (sy) startYear = curYear; if (ey) endYear = curYear;

document.getElementById('selectYear').options.length = 0; var j = 0; for (y=ey; y>=sy; y--) { document.getElementById('selectYear')[j++] = new Option(y, y); } } function hideSelect(el, superTotal) { if (superTotal >= 100) { return; } var totalChilds = el.childNodes.length; for (var c=0; c
{ var calenderEl = document.getElementById('calenderTable'); var positions = [0,0]; var positions = getParentOffset(thisTag, positions); // nieuw var thisLeft = positions[0]; var thisRight = positions[0] + thisTag.offsetWidth; var thisTop = positions[1]; var thisBottom = positions[1] + thisTag.offsetHeight; var calLeft = calenderEl.offsetLeft; var calRight = calenderEl.offsetLeft + calenderEl.offsetWidth; var calTop = calenderEl.offsetTop; var calBottom = calenderEl.offsetTop + calenderEl.offsetHeight; if ( ( // check if it overlaps horizontally (thisLeft >= calLeft && thisLeft <= calRight) || (thisRight <= calRight && thisRight >= calLeft) || (thisLeft <= calLeft && thisRight >= calRight) ) && ( // check if it overlaps vertically (thisTop >= calTop && thisTop <= calBottom) || (thisBottom <= calBottom && thisBottom >= calTop) || (thisTop <= calTop && thisBottom >= calBottom) ) ) { hideSelectTags[hideSelectTags.length] = thisTag; thisTag.style.display = 'none'; } } } else if(thisTag.childNodes.length > 0) { hideSelect(thisTag, (superTotal+1)); } }

} function closeCalender() { for (var i=0; i
Save both files in same directory along with the file calendar.css and an image 'calender.png'. To run calendar control, run calendar.html file and select the appropriate month, year and date.

When user clicks on the button adjacent to text box, a calendar will appear on the web page....

In the appeared calendar we can select month, year and date. After date selection calendar window will disappear automatically and selected date is shown in text box.

Related Documents