Você está na página 1de 103

R4R provide basic ASP.Net Tutorials concept with ASP.Net Examples . Through R4R you can develop ASP.

Net programming concept. R4R provide ASP.Net Interview Questions with answers.R4R provide ASP.Net Languages study materials in easy way.

ASP.NET Tutorials
1.1 1.2 1.3 ASP.NET Basic Tutorials (Example) Ajax with ASP.NET Basic Tutorials (Example) JavaScript with ASP.NET Basic Tutorials (Example)

ASP.NET Examples
2.1 Web Service Examples

ASP.NET Interview Questions with Answers


3.1 3.2 3.3 3.4 3.5 3.6 3.7 3.8 3.9 ASP.NET Subjective Questions with Answers ASP.NET Interview Questions with Answers ASP.NET Objective Questions And Answers ASP.NET Basic Subjective Question and Answers Ajax Subjective Questions And Answers Ajax with ASP.net Interview Questions And Answers Ajax with ASP.net Objective Questions And Answers Ajax with ASP.net Subjective Questions And Answers ASP.NET FAQs

Introduction Of ASP.NET
ASP.NET is the next generation ASP, but it's not an upgraded version of ASP. ASP.NET is an entirely new technology for server-side scripting. ASP.NET is a part of the Microsoft .NET framework, and a powerful tool for creating dynamic and interactive web pages. ASP.NET is a server side scripting technology that enables scripts (embedded in web pages) to be executed by an Internet server ASP.NET is a Microsoft Technology. ASP stands for Active Server Pages ASP.NET is a program that runs inside IIS. IIS (Internet Information Services) is Microsoft's Internet server. IIS comes as a free component with Windows servers. IIS is also a part of Windows 2000 and XP Professional.

Why is ASP.NET is Better Then ASP:


1. 2. 3. 4. 5. ASP.NET is a much improved replacement for original ASP framework All ASP.NET code is fully compiled prior to execution. ASP.NET doesn't require the use of scripting languages ASP.NET allows for total separation of code from HTML ASP.NET state management works in a Web farm environment

Page Life Cycle Of ASP.NET:

Use this event for the following: Check the IsPostBack property to determine whether this is the first time the page is PreInit being processed. Create or re-create dynamic controls. Set a master page dynamically. Set the Theme property dynamically. Init Use this event to read or initialize control properties Use this event for processing tasks that require all initialization InitComplete be complete. Use this event if you need to perform processing on your page or control before the Load event. After the Page raises this event, it loads view state PreLoad for itself and all controls, and then processes any postback data included with the Request instance. The Page calls the OnLoad event method on the Page, then recursively does Load the same for each child control, which does the same for each of its child controls until the page and all controls are loaded. Use this event for tasks that require that all other controls on the page be LoadComplete loaded. Page_PreRenderThe application is about to render the page object. Page_Unload The page is unloaded from memory. The page object is released from memory. This is the last event in the life of Page_Disposed a page object.

Architecture Of ASP.NET Framework:

In Above Figure: The configuration of ASP.NET is managed by information stored in XML-format in a configuration file (Web.Config). The cache allows for improved performance of ASP.NET, as the most commonly requested pages would be served from the ASP.NET cache.State management services for ASP.NET are provided by the ASP.NET state service. The .NET Framework provides the Common Language Runtime (CLR) , which compiles and manages the execution of ASP.NET code, and the class libraries, which offer prebuilt programmatic functionality for Web Forms, XML support, and exception handling. ADO.NET provides ASP.NET with connections to databases.

Basic Features In ASP.NET:


Easy-to-use, graphical data mapping interface Instant data transformation XSLT 1.0/2.0 and XQuery code generation Java, C#, and C++ code generation Advanced data processing functions

Support for all major relational databases including SQL Server, IBM DB2, Oracle, and more Integration with Altova StyleVision for report rendering Visual Studio & Eclipse integration Available in 32-bit and 64-bit versions

Advanced Features in ASP.NET:


Some of the new features in ASP.NET 2.0 are: Master Pages, Themes, and Web Parts Standard controls for navigation Standard controls for security Roles, personalization, and internationalization services Improved and simplified data access controls Full support for XML standards like, XHTML, XML, and WSDL Improved compilation and deployment (installation) Improved site management New and improved development tools

Some of the new features in ASP.NET 3.5 are: ASP.NET AJAX. New ListView and DataPager Controls. WCF Support for RSS, JSON, POX and Partial Trust. LINQ (Language Integrated And Query). New Web Design Interface. Multi-targeting Support.

The new assemblies that would be of use to ASP.NET 3.5 developers are as follows: System.Core.dll - Includes the implementation for LINQ to Objects System.Data.Linq.dll - Includes the implementation for LINQ to SQL System.Xml.Linq.dll - Includes the implementation for LINQ to XML System.Data.DataSetExtensions.dll - Includes the implementation for LINQ to DataSet System.Web.Extensions.dll: Includes the implementation for ASP.NET AJAX (new enhancements added) and new web controls as explained earlier.

Advantage Of ASP.NET:

1. ASP.NET drastically reduces the amount of code required to build large applications. 2. With built-in Windows authentication and per-application configuration, your
applications are safe and secured.

3. It provides better performance by taking advantage of early binding, just-in-time 4.


compilation, native optimization, and caching services right out of the box. The ASP.NET framework is complemented by a rich toolbox and designer in the Visual Studio integrated development environment. WYSIWYG editing, drag-anddrop server controls, and automatic deployment are just a few of the features this powerful tool provides.

5. Provides simplicity as ASP.NET makes it easy to perform common tasks, from simple
form submission and client authentication to deployment and site configuration. JavaScript with ASP.NET Basic Tutorials (Example)

1. First Application Using JavaScript 2. How to access a URL of parent page in ASP. net 3. Confirm Box in JavaScript 4. Prompt Box in JavaScript 5. Special Character in JavaScript 6. How to Swap a Image 7. How to show Day of Week 8. How To validate a Form in ASP.Net 9. Show a Military Clock and ordinary clock 10. JavaScript Loops 11. JavaScript Continue and Break Statements 12. JavaScript Arithmetic and Assignment Operators 13. eval() and floor() 14. join() isNAN() 15. Some Methods 16. Math, String, Number Object Methods 17. createTextNode() Method 18. blure() and assign() Method 19. link() Method in JavaScript 20. slice() Method 21. createPopup() and open() Method 22. blink() Method 23. print() Method 24. sup() and sort() Method 25. Calculator in JavaScript 26. Image Upload Control 27. Show the Clock on Button 28. Show popup window onMouseOver 29. Cookie in JavaScript 30. Sending email using JavaScript 31. Measuring users time on a page 32. Digital clock in the status line 33. Creating a Animated frame 34. Collapse (Tree) JavaScript Menu 35. How to create a field's max length

36. Selecting whole text on button Click 37. Selecting a item from Drop Down List and display it another

Text Box 38. Increases and decreases the size of image 39. Create a Popup using JavaScript 40. Generate Unicode 41. Disabling Right Click button of mouse 42. Status Bar Message 43. Monitor Information 44. Last Modify Page 45. Setting the home page
46. Change back Ground Color onMouseOver using JavaScript
First Application Using JavaScript
Step 1. Written below code in your application.

<script language="javascript"> function displayDate() { alert(Date()); } </script> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Display</title> </head> <body> <form id="form1" runat="server"> <div> <button type="button" onclick="displayDate()">DisplayDate</button> </div> </form> </body> </html>

Step 2. Run the Application. Click on Button.

How to access a URL of parent page in ASP. net


Step 1. Open a new website, add a button and textboxes control and named this page iframe.aspx. Design code is given below

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="iframe.aspx.cs" Inherits="iframe" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script language="javascript" src="JScript.js"> </script> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> </head> <body><form id="form1" runat="server"> <div> <asp:TextBox ID="TextBox1" runat="server"> </asp:TextBox> <asp:TextBox ID="TextBox2" runat="server" style="top: 66px; left: 10px; position: absolute; height: 22px; width: 128px"> </asp:TextBox> <asp:Button ID="Button1" runat="server" Text="Button" style="top: 120px; left: 12px; position: absolute; height: 26px; width: 56px" OnClientClick="uro()"/> </div> </form></body> </html> Step 2. Add a JavaScript file from Solution Explorer window

The code is written in JavaScript file is function uro() { alert(parent.document.location.href); } function url() { alert(document.location.href); } Below code written in the design page to attached the JavaScript file to your project <script language="javascript" src="JScript.js"> </script> Step 3. Add another page from new item selection menu. The design code of this page is (url.aspx)

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="url.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script language="javascript" src="JScript.js"> </script> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>url</title> </head> <body> <form id="url" runat="server"> <div> <asp:Button ID="Button1" runat="server" Text="Button" onclientclick="url()"/> <iframe src="iframe.aspx" align="middle" height="350px" name="Comments"> </iframe> </div> </form> </body> </html> Step 4. Now run the Application.

Confirm Box in JavaScript


Step 1. Written below code in your application. <html> <head> <script type="text/javascript"> function show_box() { var r=confirm("Press a button"); if (r==true) { alert("You pressed OK!"); } else { alert("You pressed Cancel!"); } } </script> </head> <body> <input type="button" onclick="show_box()" value="Confirm box" /> </body> </html>

Step 2. Run the Application. Click on Button.

Prompt Box in JavaScript


A prompt box is often used if you want the user to input a value before entering a page. Step 1. Written below code in your application. <html> <head> <script type="text/javascript"> function show_box() { var name=prompt("Please enter your name","Aditya Tiwari"); if (name!=null && name!="") { document.write("Hello " + name + "! How are you today?"); } } </script> </head> <body>

<input type="button" onclick="show_box()" value="Show" /> </body> </html> Step 2. Run the Application. Click on Button.

You Entered the Website

Special Character in JavaScript Code \' \" \\ \n \r \t \b \f Output single quote double quote backslash new line carriage return tab backspace form feed

Step 1. Written below code in your application. <html>

<head> <script type="text/javascript"> var txt="I am working in \"r4r\"."; document.write(txt); </script> </head> <body> </body> </html> Step 2. Run the Application.

How to Swap a Image using JavaScript


Step 1. Written below code in your application.

<html xmlns="http://www.w3.org/1999/xhtml"> <script language="javascript"> if (document.images) { smile = new Image happy = new Image smile.src = "http://images.zaazu.com/img/happy-rollhappy-animation-animated-smiley-emoticon-000359-large.gif" happy.src = "http://www.animationbuddy.com/Animation/Nature/Sun/Sun_happy.gif" } function imageSwap(thisImage,newImage) { if (document.images) { document[thisImage].src = eval(newImage + ".src") } } </script> <a href="http://www.r4r.co.in/" onMouseOver="imageSwap('aditya','happy')" onMouseOut="imageSwap('aditya','smile')"> <img src="http://images.zaazu.com/img/happy-roll-happy-animation -animated-smiley-emoticon-000359-large.gif" width="150" height="150" border="0" alt="Picture of Jack" name="aditya"> </a>

</script> </html>

Step 2. Run the Application. Click on Button. OnMouseOut

OnMouseOver

How to show Day of Week


Step 1. Written below code in your application. <html> <script language="javascript"> function get_day() { var getDay=new Date(); if(getDay.getDay()>0 && getDay.getDay()<6) {

} } </script> <body> <input type="button" onclick="get_day()" value="Show Day" /> </body> </html> Step 2. Run the Application. Click on Button.

alert("Its a Week Day"); } else { alert("Its Week End!!!")

How To validate a Form in ASP. Net


Step 1. Written below code in your application. JavaScript Code

<script language="javascript" type="text/javascript"> function validate() { if (document.getElementById("<%=TextBox1.ClientID%>").value=="") { alert("Name can not be blank"); document.getElementById("<%=TextBox1.ClientID%>").focus(); return false; } if(document.getElementById("<%=TextBox2.ClientID %>").value=="")

alert("Email id can not be blank"); document.getElementById("<%=TextBox2.ClientID %>").focus(); return false;

} var emailPat= /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/; var emailid=document.getElementById("<%=TextBox2.ClientID %>").value; var matchArray = emailid.match(emailPat); if (matchArray == null) { alert("Your email address seems incorrect. Please try again."); document.getElementById("<%=TextBox2.ClientID %>").focus(); return false; } if (document.getElementById("<%=TextBox3.ClientID%>").value=="") { alert("Contact Number can not be blank"); document.getElementById("<%=TextBox3.ClientID%>").focus(); return false; } var digits="0123456789"; var temp; for (var i=0;i<document.getElementById("<%=TextBox3.ClientID %>").value.length;i++) { temp=document.getElementById("<%=TextBox3.ClientID %>").value.substring(i,i+1); if (digits.indexOf(temp)==-1) { alert("Please enter correct Contact Number"); document.getElementById("<%=TextBox3.ClientID%>").focus(); return false; } } if(document.getElementById("<%=TextBox5.ClientID %>").value=="") { alert("City can not be blank"); document.getElementById("<%=TextBox5.ClientID %>").value; document.getElementById("<%=TextBox5.ClientID %>").focus(); return false; } if(document.getElementById("<%=TextBox6.ClientID %>").value=="") { alert("Password can not be blank"); document.getElementById("<%=TextBox6.ClientID %>").value; document.getElementById("<%=TextBox6.ClientID %>").focus(); return false; } if(document.getElementById("<%=TextBox7.ClientID %>").value=="") { alert("Please Re-Enter Password "); document.getElementById("<%=TextBox7.ClientID %>").value;

document.getElementById("<%=TextBox7.ClientID %>").focus(); return false; } return true; } </script>

Default.aspx Code

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Form Validation</title> </head> <body> <form id="form1" runat="server"> <script language="javascript"> //Write JavaScript Code </script> <div> <table > <tr><td>Name</td> <td><asp:TextBox ID="TextBox1" runat="server" Width="193px"></asp:TextBox></td></tr> <tr> <td>Email ID</td> <td><asp:TextBox ID="TextBox2" runat="server" Width="193px" ToolTip="Enter unique Email ID" AutoPostBack="True"> </asp:TextBox></td></tr> <tr><td>Contact Number</td><td> <asp:TextBox ID="TextBox3" runat="server" Width="193px" AutoPostBack="True"></asp:TextBox></td></tr> <tr><td> Sex</td> <td><asp:RadioButton ID="RadioButton1" runat="server" Text="Male" GroupName="a" /> <asp:RadioButton ID="RadioButton2" runat="server" Text="Female" GroupName="a" /></td> </tr> <tr> <td>Enter&nbsp; City</td> <td><asp:TextBox ID="TextBox5" runat="server" Height="22px" Width="193px"></asp:TextBox> </td></tr> <tr><td>Password</td> <td><asp:TextBox ID="TextBox6" runat="server" Width="193px" TextMode="Password" > </asp:TextBox></td> </tr> <tr><td>Re-Enter Password</td>

<td> <asp:TextBox ID="TextBox7" runat="server" TextMode="Password" Width="193px" Height="22px"></asp:TextBox> </td> </tr> <tr><td><asp:Button ID="Button1" runat="server" Text="Submit" onclick="Button1_Click" OnClientClick="return validate() " /> </td></tr></table></div> </form> </body> </html>

Step 2. Run the Application. Click on Button.

Show a Military Clock and ordinary clock


Step 1. Written below code in your application.

<html> <SCRIPT> var now; function showMilitaryTime() {

if (document.theForm.showMilitary[0].checked) { return true; } return false; } function showTheHours(theHour) { if (showMilitaryTime() || (theHour > 0 && theHour < 13)) { return (theHour); } if (theHour == 0) { return (12); } return (theHour - 12); } function showZeroFilled(inValue) { if (inValue > 9) { return ":" + inValue; } return ":0" + inValue; } function showAmPm() { if (showMilitaryTime()) { return (""); } if (now.getHours() < 12) { return (" am"); } return (" pm"); } function showTheTime() { now = new Date(); document.theForm.showTime.value = showTheHours(now.getHours()) + showZeroFilled(now.getMinutes()) + showZeroFilled(now.getSeconds()) + showAmPm(); setTimeout("showTheTime()", 1000); } </SCRIPT> <BODY onLoad="showTheTime();"> <FORM NAME="theForm"> <INPUT TYPE="TEXT" NAME="showTime"> Display Military Time? <INPUT TYPE="RADIO" NAME="showMilitary" CHECKED>Yes <INPUT TYPE="RADIO" NAME="showMilitary">No </FORM> </html> Step 2. Run the Application. Click on Button.

JavaScript Loops
The for Loop How many times the script should run then we used for loop. Syntax for (variable=startvalue;variable<=endvalue;variable=variable+increment) { //code } The while Loop The while loop loops through a block of code while a specified condition is true. Syntax while (variable<=endvalue) { //code } Example: Step 1. Written below code in your application.

<html> <body> <script type="text/javascript"> var i=0; for (i=0;i<=10;i++) { document.write("The number is " + i); document.write("<br />"); } </script> </body> </html> Step 2. Run the Application. Click on Button.

JavaScript Continue and Break Statements


The continue Statement The continue statement will break the current loop and continue with the next value. Example

<html> <body> <script type="text/javascript"> var i=0 for (i=0;i<=10;i++) { if (i==2)

{ document.write("The i); document.write("<br continue; } document.write("The document.write("<br } </script> </body> </html> Run the Code

number is continue" + />"); number is " + i); />");

The break Statement The break statement will break the loop and continue executing the code that follows after the loop. Example <html> <body> <script type="text/javascript"> var i=0; for (i=0;i<=10;i++) { if (i==2) { document.write("Time to break.." + i); document.write("<br />"); break;

} document.write("The number is " + i); document.write("<br />"); } </script> </body> </html> Execute the Code

JavaScript Arithmetic and Assignment Operators


Arithmetic Operators Arithmetic operators used to perform arithmetic operations between variables. Operator + * / % ++ --Description Addition Subtraction Multiplication Division Modulus (division remainder) Increment Decrement Decrement Example x=y+2 x=y-2 x=y*2 x=y/2 x=y%2 x=++y x=--y x=y--

Assignment Operators The assignment operator (=) is used to assign values to JavaScript variables. Operator = += -= *= /= %= Example x=y x+=y x-=y x*=y x/=y x%=y

Comparison Operators Comparison operators are used in logical statements to determine equality or difference between variables or values. Operator == === != > < >= <= Description is equal to is exactly equal to (value and type) is not equal to is greater than is less than is greater than or equal to is less than or equal to

Logical Operators Logical operators are used to determine the logic between variables or values. Operator && ! || Description and not or

Conditional Operator JavaScript also contains a conditional operator that assigns a value to a variable based on some condition. Syntax: variable_name=(condition) ? value1 : value2

eval() Method in JavaScript


Evaluates or executes an argument If the argument is an expression, eval() evaluates the expression If the argument is one or more JavaScript statements, eval() executes the statements

Syntax: eval ( string ) For example: <html>

<body> <script language="javascript"> function fun_name(){ var full_name = 'Aditya Tiwari'; var mySentence = eval('"My name is " + full_name'); alert(mySentence); } </script> <button onclick="fun_name()">Eval function</button> </body> </html> Output:

floor() Method The floor() method rounds a number to the nearest integer, and returns the result. Syntax: Math.floor (value); For Example: <html> <body> <script language="javascript"> function math_val(){ var val = 1.1; var stat = eval('"Actual value is=" + val +" "+ "After truncate value is= " + Math.floor(1.1)'); alert(stat); }

</script> <button onclick="math_val()">FLOOR</button> </body> </html> Output:

join() Method in JavaScript


Joins all array elements into a single string separated by the specified delimiter. Syntax: arrayName.join(param1) Example: <html> <body> <script language="javascript"> function join_a() { var myArray = new Array('Aditya','Anil','Ashish'); alert(myArray.join('>>')); } </script> <button onclick="join_a()">ArrayJoin</button> </body> </html> Output

isNAN function in JavaScript The isNaN() function determines whether a value is an illegal number (Not-a-Number). This function returns true if the value is NaN, and false if not. <html> <body> <button onclick="alert(isNaN('12.34'));">False_isNaN</button> <button onclick="alert(isNaN('Hello'));">True_isNaN</button> </body> </html> Output:

Some JavaScript Methods Listed below


Array Object Method Method concat() Description Joins two or more arrays, and returns a copy of the joined arrays Removes the last element of an array, and returns that element Adds new elements to the end of an array, and returns the new length Reverses the order of the elements in an array Removes the first element of an array, and returns that element

pop()

push() reverse() shift()

slice() sort() splice() toString() unshift() valueOf()

Selects a part of an array, and returns the new array Sorts the elements of an array Adds/Removes elements from an array Converts an array to a string, and returns the result Adds new elements to the beginning of an array, and returns the new length Returns the primitive value of an array

Date Object Methods Method getDate() getDay() getFullYear() getHours() getMilliseconds() getMinutes() getMonth() getSeconds() getTime() Description Returns the day of the month (from 1-31) Returns the day of the week (from 0-6) Returns the year (four digits) Returns the hour (from 0-23) Returns the milliseconds (from 0-999) Returns the minutes (from 0-59) Returns the month (from 0-11) Returns the seconds (from 0-59) Returns the number of milliseconds since midnight Jan 1, 1970

getTimezoneOffset( Returns the time difference between GMT and local time, in minutes ) getUTCDate() getUTCDay() getUTCFullYear() getUTCHours() Returns the day of the month, according to universal time (from 1-31) Returns the day of the week, according to universal time (from 0-6) Returns the year, according to universal time (four digits) Returns the hour, according to universal time (from 0-23)

getUTCMilliseconds( Returns the milliseconds, according to universal time (from 0-999) ) getUTCMinutes() getUTCMonth() Returns the minutes, according to universal time (from 0-59) Returns the month, according to universal time (from 0-11)

getUTCSeconds() getYear() parse() setDate() setFullYear() setHours() setMilliseconds() setMinutes() setMonth() setSeconds() setTime() setUTCDate() setUTCFullYear() setUTCHours()

Returns the seconds, according to universal time (from 0-59) Use the getFullYear() method instead Parses a date string and returns the number of milliseconds since midnight of January 1,1970 Sets the day of the month (from 1-31) Sets the year (four digits) Sets the hour (from 0-23) Sets the milliseconds (from 0-999) Set the minutes (from 0-59) Sets the month (from 0-11) Sets the seconds (from 0-59) Sets a date and time by adding or subtracting a specified number of milliseconds to/from midnight January 1, 1970 Sets the day of the month, according to universal time (from 1-31) Sets the year, according to universal time (four digits) Sets the hour, according to universal time (from 0-23)

setUTCMilliseconds( Sets the milliseconds, according to universal time (from 0-999) ) setUTCMinutes() setUTCMonth() setUTCSeconds() setYear() toDateString() toGMTString() Set the minutes, according to universal time (from 0-59) Sets the month, according to universal time (from 0-11) Set the seconds, according to universal time (from 0-59) Use the setFullYear() method instead Converts the date portion of a Date object into a readable string Use the toUTCString() method instead

toLocaleDateString( Returns the date portion of a Date object as a string, using locale conventions )

toLocaleTimeString( Returns the time portion of a Date object as a string, using locale conventions ) toLocaleString() toString() toTimeString() toUTCString() UTC() valueOf() Converts a Date object to a string, using locale conventions Converts a Date object to a string Converts the time portion of a Date object to a string Converts a Date object to a string, according to universal time Returns the number of milliseconds in a date string since midnight of January 1, 1970, according to universal time Returns the primitive value of a Date object

Math Object Methods


Method abs(x) acos(x) asin(x) Description Returns the absolute value of x Returns the arccosine of x, in radians Returns the arcsine of x, in radians Returns the arctangent of x as a numeric value between -PI/2 and atan(x) PI/2 radians atan2(y,x) Returns the arctangent of the quotient of its arguments ceil(x) Returns x, rounded upwards to the nearest integer cos(x) Returns the cosine of x (x is in radians) exp(x) Returns the value of Ex floor(x) Returns x, rounded downwards to the nearest integer log(x) Returns the natural logarithm (base E) of x max(x,y,z,...,n) Returns the number with the highest value min(x,y,z,...,n) Returns the number with the lowest value pow(x,y) Returns the value of x to the power of y random() Returns a random number between 0 and 1 round(x) Rounds x to the nearest integer sin(x) Returns the sine of x (x is in radians) sqrt(x) Returns the square root of x tan(x) Returns the tangent of an angle Number Object Methods Method toExponential(x) toFixed(x) Description Converts a number into an exponential notation Formats a number with x numbers of digits after the

toPrecision(x) toString() valueOf()

decimal point Formats a number to x length Converts a Number object to a string Returns the primitive value of a Number object

String Object Methods Method Description charAt() Returns the character at the specified index charCodeAt() Returns the Unicode of the character at the specified index concat() Joins two or more strings, and returns a copy of the joined strings fromCharCode() Converts Unicode values to characters Returns the position of the first found occurrence of a specified value in a indexOf() string Returns the position of the last found occurrence of a specified value in a astIndexOf() string Searches for a match between a regular expression and a string, and match() returns the matches valueOf() Returns the primitive value of a String object slice() Extracts a part of a string and returns a new string Searches for a match between a substring (or regular expression) and a replace() string, and replaces the matched substring with a new substring Searches for a match between a regular expression and a string, and search() returns the position of the match split() Splits a string into an array of substrings Extracts the characters from a string, beginning at a specified start substr() position, and through the specified number of character substring() Extracts the characters from a string, between two specified indices toLowerCase() Converts a string to lowercase letters toUpperCase() Converts a string to uppercase letters

createTextNode() Method
The createTextNode() method creates a text node. This method returns a Text object. Example: <html> <body> <script language="JavaScript"> function fnct_node() { var my_node = document.createTextNode("Good Morning!!!"); document.body.appendChild(my_node);

} </script> <button onclick="fnct_node()">Create text node</button> </body> </html> Output:

pow() Method The pow() method returns the value of x to the power of y . Example: <html> <body> <button onclick="alert(Math.pow(2,2));">POW</button> </body> </html> Output:

blure() and assign() Method in JavaScript

blure() Method in JavaScript The blur() method is used to remove focus from an element. Example: Take a example to loss the focus of Button. <html> <body> <script language="JavaScript"> function remove_focus(){ document.getElementById("removeButton").blur(); document.getElementById("removeButton").innerText = "This button lost its focus"; alert("The button lost its focus"); } </script> <input id="removeButton" type="button" onclick="remove_focus();" value="Input Focus" onFocus="this.innerText='In focus. Click me to lose focus'"> </body> </html> Output:

assign() Method in JavaScript The assign() method loads a new document. Example:

<html> <body> <script language="JavaScript"> function new_doc() { location.assign("http://r4r.co.in/"); } </script> <input type="button" value="Load new page(R4R)" onclick="new_doc();"> </body> </html> Output:

link() Method in JavaScript


The link() method is used to display a string as a hyperlink. This method returns the string embedded in the <a> tag, like this: <a href="url">string</a> Syntax: string.link(url); Example: <html> <body> <script language="javascript"> function new_url() { var myS = new String('r4r.co.in Home Page'); document.write(myS.link('http://www.r4r.co.in/')); } </script> <button onclick="new_url()">Create a link from</button> </body> </html> Output:

slice() Method
The slice() method extracts a part of a string and returns the extracted part in a new string. Syntax: string.slice(begin,end) Example: <html> <body> <script> function slice_string() { var myName = new String('Aditya Tiwari'); alert(myName+'\n'+"After Slice="+ myName.slice(1,6)); } </script> <button onclick="slice_string()">Slice of Name</button> </body> </html> Output:

How to use createPopup() Method in JavaScript


The createPopup() method is used to create a pop-up window. Its only support the Internet Explorer

Syntax: window.createPopup() Example: <html> <body> <script language="JavaScript"> var pop_window; function new_window() { pop_window = window.createPopup(); pop_window.document.body.style.backgroundColor = 'red'; pop_window.show(100,100,100,200,document.body); } </script> <input type="button" value="Popup Window" onclick="new_window();"> </body> </html> Out Put: Click on Popup window button.

How to use open() Method in JavaScript Example: <html> <head> <script type="text/javascript"> function new_window() { myWindow=window.open('','','width=200,height=100'); myWindow.document.write("<p>This is new window</p>"); } </script> </head> <body> <input type="button" value="Open New Window" onclick="new_window()" /> </body> </html> Out Put:

How to use blink() Method in JavaScript


The blink() method is used to display a blinking string. The blink() method only works in Firefox and Opera. It is not supported in Internet Explorer, Chrome, or Safari.

Syntax: string.blink() Example: <html> <body> <script language="javascript"> function win_blink() { var myString = new String('Am I blinking?'); document.write(myString.blink()); } </script> <button onclick="win_blink()">Blink</button> </body> </html> Out Put:

How to use print() Method in JavaScript


The print() method prints the contents of the current window. Syntax: window.print() Example: <html> <body> <script language="JavaScript"> function print_win() { window.print(); } </script> <input type="button" value="Print" onclick="print_win();"> </body> </html> Out Put:

How to use sup() Method in JavaScript


The sup() method is used to display a string as superscript text. Syntax: string.sup() Example: <html> <body> <script language="javascript"> function sup_win() { var myString = new String('Two'); document.write('Square'+myString.sup()); } </script> <button onclick="sup_win()"> sup me</button>

</body> </html> Out Put:

How to use sort() Method in JavaScript The sort() method sorts the elements of an array. Syntax: array.sort(sortfunc) Example: <html> <body> <script language="javascript"> function sort_array() { var myString = new Array('Anil','Aditya','Ashish'); myString.sort(); alert(myString); } </script> <button onclick="sort_array()">Sort Array</button> </body> </html> Out Put:

Calculator in JavaScript
<html> <body> <center> <form name="keys" action=""> <table> <B> <table border=2 width=50 height=60 cellpadding=1 cellspacing=5> <tr> <td colspan=3 align=middle> <input name="readText" type="Text" size=24 value="0" width=100%> </td> <td </td> <td> <input name="buttonClear" type="Button" value=" C " onclick="Clear()"> </td> <td><input name="buttonClearEntry" type="Button" value=" CE " onclick="ClearEntry()"> </td> </tr> <tr> <td> <input name="btnSeven" type="Button" value=" 7 " onclick="number_press(7)"> </td> <td> <input name="btnEight" type="Button" value=" 8 " onclick="number_press(8)"> </td> <td> <input name="btnNine" type="Button" value=" 9 " onclick="number_press(9)">

</td> <td> </td> <td> <input name="btnNeg" type="Button" value=" +/- " onclick="Neg()"> </td> <td> <input name="btnPercent" type="Button" value=" % " onclick="Percent()"> </td> </tr> <tr> <td> <input name="btnFour" type="Button" value=" 4 " onclick="number_press(4)"> </td> <td> <input name="btnFive" type="Button" value=" 5 " onclick="number_press(5)"> </td> <td> <input name="btnSix" type="Button" value=" 6 " onclick="number_press(6)"> </td> <td> </td> <td align=middle><input name="btnPlus" type="Button" value=" + " onclick="Operation('+')"> </td> <td align=middle><input name="btnMinus" type="Button" value=" - " onclick="Operation('-')"> </td> </tr> <tr> <td> <input name="btnOne" type="Button" value=" 1 " onclick="number_press(1)"> </td> <td> <input name="btnTwo" type="Button" value=" 2 " onclick="number_press(2)"> </td> <td> <input name="btnThree" type="Button" value=" 3 " onclick="number_press(3)"> </td> <td> </td> <td align=middle><input name="btnMultiply" type="Button" value=" * " onclick="Operation('*')"> </td> <td align=middle><input name="btnDivide" type="Button" value=" / " onclick="Operation('/')"> </td>

</tr> <tr> <td> <input name="btnZero" type="Button" value=" 0 " onclick="number_press(0)"> </td> <td> <input name="btnDecimal" type="Button" value=" . " onclick="Decimal()"> </td> <td colspan=3> </td> <td> <input name="btnEquals" type="Button" value=" = " onclick="Operation('=')"> </td> </tr> </table> </table> </B> </form> </center> <font face="Verdana, Arial, Helvetica" size=2> <script language="JavaScript"> var funKeyPad = document.keys; var Accumulate = 0; var NewNum = false; var PendingOp = ""; function number_press (Num) { if (NewNum) { funKeyPad.readText.value = Num; NewNum = false; } else { if (funKeyPad.readText.value == "0") funKeyPad.readText.value = Num; else funKeyPad.readText.value += Num; } } function Operation (Op) { var Readout = funKeyPad.readText.value; if (NewNum && PendingOp != "="); else { NewNum = true; if ( '+' == PendingOp ) Accumulate += parseFloat(Readout); else if ( '-' == PendingOp ) Accumulate -= parseFloat(Readout); else if ( '/' == PendingOp ) Accumulate /= parseFloat(Readout);

else if ( '*' == PendingOp ) Accumulate *= parseFloat(Readout); else Accumulate = parseFloat(Readout); funKeyPad.readText.value = Accumulate; PendingOp = Op; } } function Decimal () { var curReadOut = funKeyPad.readText.value; if (NewNum) { curReadOut = "0."; NewNum = false; } else { if (curReadOut.indexOf(".") == -1) curReadOut += "."; } funKeyPad.readText.value = curReadOut; } function ClearEntry () { funKeyPad.readText.value = "0"; NewNum = true; } function Clear () { Accumulate = 0; PendingOp = ""; ClearEntry(); } function Neg () { funKeyPad.readText.value = parseFloat(funKeyPad.readText.value) * -1; } function Percent () { funKeyPad.readText.value = (parseFloat(funKeyPad.readText.value) / 100) * parseFloat(Accumulate); } </script> </body> </html> Out Put:

How to use Image Upload control in JavaScript


Step 1. Written below code in your application. <html> <script language="javascript"> var maxWidth=100; var maxHeight=100; var fileTypes=["bmp","gif","png","jpg","jpeg"]; var outImage="previewField"; var defaultPic="spacer.gif"; function preview(what){ var source=what.value; var ext=source.substring(source.lastIndexOf(".") +1,source.length).toLowerCase(); for (var i=0; i<fileTypes.length; i++) if (fileTypes[i]==ext) break; globalPic=new Image(); if (i<fileTypes.length) globalPic.src=source; else { globalPic.src=defaultPic; alert("That is not avalid image\nPlease load an image with an extention of one of the following:\n\n"+fileTypes.join(", ")); } setTimeout("apply_changed()",200); } var globalPic; function apply_changed(){ var field=document.getElementById(outImage); var x=parseInt(globalPic.width); var y=parseInt(globalPic.height); if (x>maxWidth) {

y*=maxWidth/x; x=maxWidth; } if (y>maxHeight) { x*=maxHeight/y; y=maxHeight; } field.style.display=(x<1 || y<1)?"none":""; field.src=globalPic.src; field.width=x; field.height=y;

} </script> <body> <input type="file" id="picField" onchange="preview(this)"> </body> </html> Step 2. Run the Application. Click on Button.

How to show the Clock on Button using JavaScript


Step 1. Written below code in your application. <html> <script language="javascript"> function get_date() { Todays = new Date(); TheDate = "" + (Todays.getMonth()+ 1) +" / "+ Todays.getDate() + "/"+ Todays.getYear() document.clock.date.value = TheDate; } var timerID = null; var timerRunning = false; function stopclock (){ if(timerRunning);

clearTimeout(timerID); timerRunning = false; } function startclock () { stopclock(); get_date() showtime(); } function showtime () { var now = new Date(); var hours = now.getHours(); var minutes = now.getMinutes(); var seconds = now.getSeconds() var timeValue = "" + ((hours >12) ? hours -12 :hours) timeValue += ((minutes < 10) ? ":0" : ":") + minutes timeValue += ((seconds < 10) ? ":0" : ":") + seconds timeValue += (hours >= 12) ? " P.M." : " A.M." document.clock.face.value = timeValue; timerID = setTimeout("showtime()",1000); timerRunning = true; } </script> <body onLoad="startclock()"> <form name="clock" onSubmit="0"> Date: <input type=text name="date" size=12 value=""> <br /> Time:<input type=button name="face" size=12 value="JavaScript!!"> </form> </html> Step 2. Run the Application.

How to show popup window onMouseOver using JavaScript


Step 1. Written below code in your application. <html> <body> <script language="javascript">

var popup_window = null; function popup(status,url) { if(status != 0) { if(popup != null) popup.focus(); else { var popup = open(url, "Popup", "width=350,height=175"); popup_window = popup; } } else { if(popup_window != null) popup_window.close(); } } </script> <center><a href="" onMouseover="popup(1,'http://r4r.co.in/test')" onMouseout="popup(0)"> <img src="font face="Verdana">http://r4r.co.in/g.jpg" width=200 height=200></a> </center> </body> </html> Step 2. Run the Application.

Cookie in JavaScript
Step 1. Written below code in your application. <html> <body> <script> function get_Cookie_Val (offset) { var end_string = document.cookie.indexOf (";", offset); if (end_string == -1) end_string = document.cookie.length; return unescape(document.cookie.substring(offset, end_string)); } function get_cookie (name) { var arg = name + "="; var str_lngt = arg.length; var cookie_length = document.cookie.length; var i = 0; while (i < cookie_length) {

} function set_cookie (name, value) { var argv = set_cookie.arguments; var argc = set_cookie.arguments.length; var expires = (argc > 2) ? argv[2] : null; var path = (argc > 3) ? argv[3] : null; var domain = (argc > 4) ? argv[4] : null; var secure = (argc > 5) ? argv[5] : false; document.cookie = name + "=" + escape (value) + ((expires == null) ? "" : ("; expires=" + expires.toGMTString())) + ((path == null) ? "" : ("; path=" + path)) + ((domain == null) ? "" : ("; domain=" + domain)) + ((secure == true) ? "; secure" : ""); } function DeleteCookie (name) { var exp = new Date(); exp.setTime (exp.getTime() - 1); var cval = get_cookie (name); document.cookie = name + "=" + cval + "; expires=" + exp.toGMTString(); } </script> <form name="demoForm" onSubmit=" if(demoForm.Username.value.length != 0) { var expdate = new Date (); expdate.setTime(expdate.getTime() + (24 * 60 * 60 * 1000)); set_cookie('Demoname', demoForm.Username.value, expdate); alert('Hey ' + demoForm.Username.value + ', how is it going? Now all you have to do is click Enter'); return false; } else { alert('You left the name field blank.'); return false; }"> <center><p><font size=+1>Enter Your name Here To Request Access : </font></font></i> </b><input type="text" name="Username" size=40></p></center> <center><p><input type="submit" value="Submit Request"><input type="button" value="Enter" onClick=" if(get_cookie('Demoname') == null) alert('Did you submit request?') else window.open('j15b.htm', '_top')">

} return null;

var j = i + str_lngt; if (document.cookie.substring(i, j) == arg) return get_Cookie_Val (j); i = document.cookie.indexOf(" ", i) + 1; if (i == 0) break;

</form> </body> </html> Step 2. Run the Application. Enter your name and click to Enter the site.

Measuring users time on a page using Java Script


Step 1. Written below code in your application. <html> <body bgcolor=ffffff onLoad='personIN()' onUnLoad='personOut()'> <script language="javascript"> function personIN() { enter=new Date(); } function personOut() { exit=new Date(); time_dif=(exit.getTime()-enter.getTime())/1000; time_dif=Math.round(time_dif); alert ("You've only been here for: " + time_dif + " seconds!!") } </script> </body> </html>

Step 2. Run the Application.

How to show a digital clock in the status line


Step 1. Written below code in your application. <html> <body onload="displyTime_inStatusLine()"> <script language="javascript"> function displyTime_inStatusLine() { var d = new Date(); var h = d.getHours(); var m = d.getMinutes(); var ampm = (h >= 12)?"PM":"AM"; if (h > 12) h -= 12; if (h == 0) h = 12; if (m < 10) m = "0" + m; var t = h + ':' + m + ' ' + ampm; defaultStatus = t; setTimeout("displyTime_inStatusLine()", 60000); } </script>

</body> </html> Step 2. Run the Application.

How to Creating a Animated frame


Step 1. Written below code in your application. <html> <body onload="changeOneFrame()"> <script language="javascript"> var newWin = window.open('', 'f', 'width=400,height=400'); newWin.document.write('<frameset rows="50%,50%" cols="50%,50%">'); newWin.document.write('<frame name="f1" src="about:blank">'); newWin.document.write('<frame name="f2" src="about:blank">'); newWin.document.write('<frame name="f3" src="about:blank">'); newWin.document.write('<frame name="f4" src="about:blank">'); newWin.document.write('</frameset>'); colors = new Array("red","green","blue","yellow","white"); windows = new Array(newWin.f1, newWin.f2, newWin.f4, newWin.f3); var c = 0, f = 0; var timeout = null; function changeOneFrame() {

} </script> <input type="button" value="Stop" onclick="if (timeout) clearTimeout(timeout); if (!n.closed) n.close();" /> </body> </html> Step 2. Run the Application.

windows[f].document.write('<BODY BGCOLOR="' + colors[c] + '">'); windows[f].document.close(); f = (f + 1) % 4; c = (c + 1) % 5; timeout = setTimeout("changeOneFrame()", 250);

How to create Collapse Menu in JavaScript


Step 1. Written below code in your application.

<html> <body> <script language="javascript"> function open_subCategory(n, nn) { var i = 0 for(i=1;i<n+1;i++) { var sel = document.getElementById('insideSubCategory'+i); sel.style.display = 'none'; } var sel = document.getElementById('insideSubCategory'+nn); sel.style.display = 'block'; } function openInside_subCategory(n, nn) { var i = 0 for(i=1;i<n+1;i++) { var sel = document.getElementById('showProducts'+i); sel.style.display = 'none'; } var sel = document.getElementById(nn); sel.style.display = 'block'; } </script> <div style="display:block; cursor:pointer; font-size: large; font-weight: bold;"> <a href="JavaScript:open_subCategory(2, 1)">Fruit</a></div> <div id="insideSubCategory1" style="border:1px solid white; display:none;"> <div style="display:block; padding-left:6px;"> <a href="JavaScript:openInside_subCategory(2, 'showProducts1')">Orange</a></div> <div id="showProducts1" style="margin:6px; font-size:9px; border:1px solid white; display:none;"> <div style="display:block; padding-left:12px;"> <a href="#">Yellow</a></div> </div> <div style="display:block; padding-left:6px;"> <a href="JavaScript:openInside_subCategory(2, 'showProducts2')">Apple</a></div> <div id="showProducts2" style="margin:6px; font-size:9px; border:1px solid white; display:none;"> <div style="display:block; padding-left:12px;"><a href="#">Red</a></div> <div style="display:block; padding-left:12px;"><a href="#">Green</a></div> </div> <div style="display:block; padding-left:6px;"> <a href="JavaScript:openInside_subCategory(2, 'showProducts3')">Banana</a></div> <div id="showProducts3" style="margin:6px; font-size:9px; border:1px solid white; display:none;"> <div style="display:block; padding-left:12px;"><a href="#">Yellow</a></div> </div> </div> <div style="display:block; cursor:pointer; font-size: large; font-weight: bold;"> <a href="JavaScript:open_subCategory(2, 2)">Vegitable</a></div> <div id="insideSubCategory2" style="border:1px solid white; display:none;"> <div style="display:block; padding-left:6px;"> <a href="JavaScript:openInside_subCategory(3, 'showProducts4')">Tomato</a></div> <div id="showProducts4" style="margin:6px; font-size:9px; border:1px solid white;

display:none;"> <div style="display:block; padding-left:12px;"><a href="#">Red</a></div> </div> <div style="display:block; padding-left:6px;"> <a href="JavaScript:openInside_subCategory(3, 'showProducts5')">Brinjal</a></div> <div id="showProducts5" style="margin:6px; font-size:9px; border:1px solid white; display:none;"> <div style="display:block; padding-left:12px;"><a href="#">Purple</a></div> <div style="display:block; padding-left:12px;"><a href="#">White</a></div> </div> <div style="display:block; padding-left:6px;"> <a href="JavaScript:openInside_subCategory(3, 'showProducts6')">Pea</a></div> <div id="showProducts6" style="margin:6px; font-size:9px; border:1px solid white; display:none;"> <div style="display:block; padding-left:12px;"><a href="#">Green</a></div> </div> </div> <div style="display:block; cursor:pointer; font-size: large; font-weight: bold;"> <a href="JavaScript:open_subCategory(2, 3)">Grains</a></div> <div id="insideSubCategory3" style="border:1px solid white; display:none;"> <div style="display:block; padding-left:6px;"> <a href="JavaScript:openInside_subCategory(4, 'showProducts7')">Rice</a></div> <div id="showProducts7" style="margin:6px; font-size:9px; border:1px solid white; display:none;"> <div style="display:block; padding-left:12px;"><a href="/">Sabarmati</a></div> <div style="display:block; padding-left:12px;"><a href="/">Basmati</a></div> <div style="display:block; padding-left:12px;"><a href="/">Saryu</a></div> </div> <div style="display:block; padding-left:6px;"> <a href="JavaScript:openInside_subCategory(4, 'showProducts8')">Wheat</a></div> <div id="showProducts8" style="margin:6px; font-size:9px; border:1px solid white; display:none;"> <div style="display:block; padding-left:12px;"><a href="/">Shakti</a></div> <div style="display:block; padding-left:12px;"><a href="/">Ashirvad</a></div> </div> <div style="display:block; padding-left:6px;"> <a href="JavaScript:openInside_subCategory(4, 'showProducts9')">Pulse</a></div> <div id="showProducts9" style="margin:6px; font-size:9px; border:1px solid white; display:none;"> <div style="display:block; padding-left:12px;"><a href="/">Chana</a></div> <div style="display:block; padding-left:12px;"><a href="/">Matar</a></div> </div> </div> </body> </html>

Step 2. Run the Application.

How to create a field's max length using JavaScript


Step 1. Written below code in your application <html> <script language="javascript"> function chek_leng(x,y) { if (y.length==x.maxLength) { var next=x.tabIndex if (next<document.getElementById("myForm").length) { document.getElementById("myForm").elements[next].focus() } } } </script> <body> <p>Enter your key value:</p> <form id="myForm"> <input size="4" tabindex="1" maxlength="4" onkeyup="chek_leng(this,this.value)"> <input size="2" tabindex="2" maxlength="2" onkeyup="chek_leng(this,this.value)"> <input size="3" tabindex="3" maxlength="3" onkeyup="chek_leng(this,this.value)"> </form>

</body> </html> Step 2. Run the Application.

Selecting whole text on button Click


Step 1. Written below code in your application <html> <script type="text/javascript"> function select_text() { document.getElementById("myText").select() } </script> <body> <input size="25" type="text" id="myText" value="Have a nice day"> <input type="button" value="Select text" onclick="select_text()"> </body> </html> Step 2. Run the Application.

Selecting a item from Drop Down List and display it another Text Box using JavaScript
Step 1. Written below code in your application <html> <script type="text/javascript"> function favrt_browser() { var mylist=document.getElementById("myList") document.getElementById("favorite").value=mylist.options[mylist.selectedIndex].text } </script> <body> <form> Select your city: <select id="myList" onchange="favrt_browser()"> <option>Delhi</option> <option>Nashik</option> <option>Varansi</option> <option>Kanpur</option> <option>Lucknow</option> <option>Allahabad</option> </select> <input type="text" id="favorite" size="20"> </form> </body> </html> Step 2. Run the Application.

How to Increases and decreases the size of image using JavaScript


Step 1. Written below code in your application. <html> <script type="text/javascript"> function changeSize(x,y) { var x; var y; document.getElementById("compman").height=x; document.getElementById("compman").width=y; } </script> <body> <img id="compman" src="Image.jpg" width="100" height="100" /> <br /><br /> <input type="button" onclick="changeSize(150,150)" value="150X150"> <br /> <input type="button" onclick="changeSize(200,200)" value="200X200"> <br /> <input type="button" onclick="changeSize(300,300)" value="300X300"> </body> </html> Step 2. Run the Application.

How to Create a Popup using JavaScript


Step 1. Written below code in your application. HTML Code:

<html> <script language="javascript"> x = 20; y = 70; function set_visible(obj) { obj = document.getElementById(obj); obj.style.visibility = (obj.style.visibility == 'visible') ? 'hidden' : 'visible'; } function place_It(obj) {

obj = document.getElementById(obj); if (document.documentElement) { theLeft = document.documentElement.scrollLeft; theTop = document.documentElement.scrollTop; } else if (document.body) { theLeft = document.body.scrollLeft; theTop = document.body.scrollTop; } theLeft += x; theTop += y; obj.style.left = theLeft + 'px' ; obj.style.top = theTop + 'px' ; setTimeout("place_It('layer1')",500); } window.onscroll = setTimeout("place_It('layer1')",500); </script> <body> <div id="layer1"> <span id="close"><a href="javascript:set_visible('layer1')" style="textdecoration: none"> <strong>Close</strong></a></span> <p>Java Script was developed by the Brendan Eich of Netscape. Initially java script was called Live script. Live script was the official name of java script when it was released in beta version in Netscape Navigator 2.0 in 1995. But it was renamed by joint procession of Sun Microsystems and Netscape .</p> </div> <input type="button" value="Open popup" onclick="set_visible('layer1')"> </body> </html>

Style Code: <style type="text/css"> #layer1 { position: absolute; visibility: hidden; width: 300px; height: 300px; left: 20px; top: 300px; background-color: #ccc; border: 2px solid #000; padding: 10px; }

#close { } float: right;

Step 2. Run the Application.

How to Generate Unicode using JavaScript


Step 1. Written below code in your application. <html> <head> <script language="JavaScript"> function toUnicode() { var str=document.myForm.myInput.value

if (str!="") { unicode=str.charCodeAt(0) } document.myForm.unicode.value=unicode } </script> </head> <body> <form name="myForm"> Enter a character:<br /> <input size="1" name="myInput" maxlength="1" onkeyup="toUnicode()"> <hr /> Unicode character:<br /> <input size="3" name="unicode"> </form> </html>

Step 2. Run the Application.

How to Disabling Right Click button of mouse using JavaScript


Step 1. Written below code in your application. <html> <head> <script language="JavaScript"> function disable() { if (event.button == 2) {

alert("Sorry no rightclick on this page.\nNow you can not view my source\n and you can not steal my images") } } </script> </head> <body onmousedown="disable()"> <form> <a href="#">Good Morning!!!!</a> <p>Have a Nice Day!!!</p> <p>Have a great Day!!!</p> <img src=Image.jpg /> </form> </body> </html> Step 2. Run the Application.

Status Bar Message using Java Script


Step 1. Written below code in your application. <html> <head> <script language="javascript"> function scrollit_r21(seed) { var msg=" Hi...this is status bar message.. you can use it in your web Application!" var out = " "; var c = 1; if (seed > 100) { seed--;

var cmd="scrollit_r21(" + seed + ") "; timerTwo=window.setTimeout(cmd, 100) ; } else if (seed <= 100 && seed > 0) { for (c=0 ; c < seed ; c++) { out+=" "; } out+=msg; seed--; var cmd="scrollit_r21(" + seed + ") "; window.status=out; timerTwo=window.setTimeout(cmd, 100); } else if (seed <= 0) { if (-seed < msg.length) { out+=msg.substring(-seed,msg.length); seed--; var cmd="scrollit_r21(" + seed + ")"; window.status=out; timerTwo=window.setTimeout(cmd, 100) ; } else { window.status=" "; timerTwo=window.setTimeout("scrollit_r21(100)",75); } } } </script> </head> <body onLoad="timerONE=window.setTimeout ('scrollit_r21(100) ' ,500) ;"> </body> </html>

Step 2. Run the Application.

How to get Monitor Information using JavaScript


Step 1. Written below code in your application. <html> <body>

<script language="JavaScript"> document.write("Screen Resolution: ") document.write(screen.width + "*") document.write(screen.height + "<br>") document.write("Available View Area: ") document.write(window.screen.availWidth + "*") document.write(window.screen.availHeight + "<br>") document.write("Color Depth: ") document.write(window.screen.colorDepth + "<br>") </script> </body> </html> Step 2. Run the Application.

How to know Last Modify Page using Java Script


Step 1. Written below code in your application. <html> <body> This page was last modify: <br /> <script language="JavaScript"> document.write(document.lastModified) </script> <br /> <br /> View source to see how it is done </body> </html> Step 2. Run the Application.

How to Set the home page


Step 1. Written below code in your application. <html> <head> <script language="JavaScript"> function Dflt(element) { element.style.behavior='url(#default#homepage)'; element.setHomePage('http://www.r4r.co.in'); } </script> </head> <body> <p>Click the button to get your home page.</p> <form> <input type="button" onclick="Dflt(this)" value="Make r4r your default homepage"> </form> </body> </html> Step 2. Run the Application.

Change back Ground Color onMouseOver using JavaScript


Step 1. Written below code in your application. <html> <body> <a href="" onmouseover ="document.bgColor='silver'"><b>Silver</b></a> <a href="" onmouseover="document.bgColor='green'"><b>Green</b></a> <a href="" onmouseover="document.bgColor='blue'"><b>Blue</b></a> <a href="" onmouseover="document.bgColor='red'"><b>Red</b></a> </body> </html> Step 2. Run the Application. When mouse on silver label back ground color changed to silver.

Web Service Examples

How To make a Web Services ( To Calculate Circle area using C#)


Step 1. Start a New Web Site

Click on ASP.Net Web Services and named your service CircleArea and press on OK Step 2. The code written for your application which return area of circle (Service.cs). This service contain a CircleArea method which calculate the area. using System; using System.Linq; using System.Web; using System.Web.Services; using System.Web.Services.Protocols; using System.Xml.Linq; [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] public class Service : System.Web.Services.WebService { public Service () { } [WebMethod (Description="To calculate Area of Circle")] public double CircleArea(int a) {return 3.14 * (a * a);} } Step 3. Run your service.

Click on CircleArea. Service is run and when you input value the result be shown.

If you want to see Service Description. Click on Service Description

Now Web service is Created. 1. If you want to know how to Use this service in Your ASP.Net Application

Click

Here.
2.

Click Here how to use in Console Application.

How to Use web Services in Console Application using C#


Step 1. Open a new project and select console Application. press on Ok.

Step 2. Click on Add service reference a new window open Click on Advance,

A new window open click on Add Web reference and copy the URL of your running service and paste it to the URL space in new window shown below and click on Go. Click on Add reference but remember your Web reference name

The Service will be added in your project

Step 3. Written the following code in your Program (Program.cs) using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; namespace Circlearea { class Program { static void Main(string[] args) { localhost.Service lo = new localhost.Service(); Console.Write("Please enter the value="); int area = Convert.ToInt32(Console.ReadLine()); double fr=lo.CircleArea(area); Console.WriteLine("Area is =" + fr); Console.ReadLine(); } } } Step 4. Run the Application

Create a Web Service For Calculate Age when user input Date
Step 1. Open a new Web Site and click on ASP.Net Web Services press on OK as shown below in fig.

Step 2. The code (Service.cs) written for Calculating Age , Calculate Factorial and Square Root of a Number. using System; using System.Linq; using System.Web; using System.Web.Services; using System.Web.Services.Protocols; using System.Xml.Linq; [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] public class Service : System.Web.Services.WebService {[WebMethod (Description="Calculating Age")] public string calAge(DateTime date) { DateTime nowDate = System.DateTime.Now; System.TimeSpan span = nowDate - date; int days = (int)span.TotalDays; int yea = days / 365; string age = yea.ToString() + " years "; return age;} [WebMethod(Description = "Calculating

SquareRoot")] public double calSquareRoot(int a) { double i = 0; double x1, x2=0; while ((i * i) <= a) i += 0.1; x1 = i; for (int j = 0; j < 10; j++) { x2 = a; x2 /= x1; x2 += x1; x2 /= 2; x1 = x2;} return x2;} [WebMethod(Description = "Calculating Factorial")] public double calFactorial(int a) {if (a == 0)return 1; else return (a*calFactorial(a-1));}}

Step 3. Debug The service

Click on each link and check your service Step 4. To use this service, go to your project solution right click and click on Add Web Reference. A new window open

Copy the URL of your running web service and paste it in the new window place as shown in below fig.

Note: Remember the web reference name, it will be added in your project (.cs ) file e.g. this reference help to call the method of your web services. You will call the methods to create an object of SERVICE. To know more click Here using localhost; Click on Add Reference, The service will be added in your web site. It will be show on your page like below fig.

How to Use web Services in ASP. Net using C#


Step 1. Run Your Service and open a new Website, Add a label and one textBox to enter radius of Circle

Click on Add web Reference

Copy the URL of Your running web Service and paste it in Your Web Reference window

Click on Go Step 2. You can change your Web reference name but you remember this. click on add Reference

The service will be added in your application

Step 3. Now add the Web reference (name space) in your application (shown below). written the following code in your .cs file (Default.aspx.cs). using System; using System.Configuration; using System.Web; using System.Data; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using localhost; public partial class _Default : System.Web.UI.Page { Service ser = new Service(); protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { double area = ser.CircleArea(int.Parse(TextBox1.Text)); Label2.Text = "Area is : " + area.ToString(); } } Step 4. Run your application (Necessary to running your web service which you use in your application)

How to Use web Services in Console Application using C#


Step 1. Open a new project and select console Application. press on Ok.

Step 2. Click on Add service reference a new window open Click on Advance,

A new window open click on Add Web reference and copy the URL of your running service and paste it to the URL space in new window shown below and click on Go. Click on Add reference but remember your Web reference name

The Service will be added in your project

Step 3. Written the following code in your Program (Program.cs) using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; namespace Circlearea { class Program { static void Main(string[] args) { localhost.Service lo = new localhost.Service(); Console.Write("Please enter the value="); int area = Convert.ToInt32(Console.ReadLine()); double fr=lo.CircleArea(area); Console.WriteLine("Area is =" + fr); Console.ReadLine(); } } } Step 4. Run the Application

Javascript Interview Questions And Answers

Page 1
Ques: 1 What is JavaScript? Ans: JavaScript is a platform-independent,event-driven, interpreted client-side scripting and programming language developed by Netscape Communications Corp. and Sun Microsystems. Ques: 2 How to detect the operating system on the client machine? Ans: In order to detect the operating system on the client machine, the navigator.appVersion string (property) should be used. Ques: 3 How to read and write a file using javascript? Ans: I/O operations like reading or writing a file is not possible with clientside javascript. However , this can be done by coding a Java applet that reads files for the script. Ques: 4 Where are cookies actually stored on the hard disk? Ans: This depends on the user's browser and OS. In the case of Netscape with Windows OS, all the cookies are stored in a single file called cookies.txt c:\Program Files\Netscape\Users\username\cookies.txt In the case of IE,each cookie is stored in a separate file namely username@website.txt. c:\Windows\Cookies\username@Website.txt Ques: 5 What can javascript programs do? Ans: Generation of HTML pages on-the-fly without accessing the Web server. The user can be given control over the browser like User input validation Simple computations can be performed on the client's machine The user's browser, OS, screen size, etc. can be detected Date and Time Handling Ques: 6 How to set a HTML document's background color? Ans: document.bgcolor property can be set to any appropriate color e.g. document.bgcolor=#ffff; Ques: 7 What is reason of the "Access is Denied" ? Ans: The "Access Denied" error in any browser is due to the following reason.

A javascript in one window or frame is tries to access another window or frame whose document's domain is different from the document containing the script Ques: 8 Is a javascript script faster than an ASP script? Ans: Yes. Since javascript is a client-side script it does require the web server's help for its computation,so it is always faster than any server-side script like ASP,PHP,JSP etc. Ques: 9 Are Java and JavaScript the Same? Ans: No. Java and javascript are two different languages. Java is a powerful object - oriented programming language like C++,C whereas Javascript is a client-side scripting language with some limitations. Ques: 10 How to embed javascript in a web page? Ans: javascript code can be embedded in a web page between <script langugage="javascript"></script> tags Ques: 11 How to access an external javascript file that is stored externally and not embedded? Ans: This can be achieved by using the following tag between head tags or between body tags. <script src="abc.js"></script> where abc.js is the external javscript file to be accessed. Ques: 12 What is the difference between an alert box and a confirmation box? Ans: An alert box displays only one button which is the OK button whereas the Confirm box displays two buttons namely OK and cancel. Ans: alert comes with one button only and confirm box comes with two button and return true and false value Ans: An alert box displays only one button which is the OK button whereas the Confirm box displays two buttons namely OK and cancel. Ques: 13 What is a prompt box? Ans: A prompt box allows the user to enter input by providing a text box. Ques: 14 Can javascript code be broken in different lines? Ans: Breaking is possible within a string statement by using a backslash \ at the end but not within any other javascript statement.that is , document.write("Hello \ world"); is possible but not document.write \ ("hello world"); Ques: 15 How to hide javascript code from old browsers that dont run it? Ans: Use the below specified style of comments <script language=javascript> <!--

javascript code goes here // --> or Use the <NOSCRIPT>some html code </NOSCRIPT> tags and code the display html statements between these and this will appear on the page if the browser does not support javascript. Ques: 16 How to comment javascript code? Ans: Use // for line comments and /* */ for block comments Ques: 17 Name the numeric constants representing max,min values Ans: Number.MAX_VALUE Number.MIN_VALUE Ques: 18 What does javascript null mean? Ans: The null value is a unique value representing no value or no object. It implies no object, or null string, no valid boolean value,no number and no array object. Ques: 19 What does undefined value mean in javascript? Ans: Undefined value means the variable used in the code doesnt exist or is not assigned any value or the property doesnt exist. Ques: 20 What is the difference between undefined value and null value? Ans: A. Undefined value cannot be explicitly stated that is there is no keyword called undefined whereas null value has keyword called null B. typeof undefined variable or property returns undefined whereas typeof null value returns object

Javascript Interview Questions And Answers

Page 1
Ques: 1 How can JavaScript make a Web site easier to use? That is, are there certain JavaScript techniques that make it easier for people to use a Web site? Ans: JavaScript's greatest potential gift to a Web site is that scripts can make the page more immediately interactive, that is, interactive without having to submit every little thing to the server for a server program to re-render the page and send it back to the client. For example, consider a top-level navigation panel that has, say, six primary image map links into subsections of the Web site. With only a little bit of scripting, each map area can be instructed to pop up a more detailed list of links to the contents within a subsection whenever the user rolls the cursor atop a map area. With the help of that popup list of links, the user with a scriptable browser can bypass one intermediate menu page. The user without a scriptable browser (or who has disabled JavaScript) will have to drill down through a more traditional and time-consuming path to the desired content. Ques: 2 Whats a way to append a value to an array? Ans: arr[arr.length] = value; Ques: 3 How do you assign object properties?

Ans: obj["age"] = 17 or obj.age = 17. Ques: 4 How do you create a new object in JavaScript? Ans: var obj = new Object(); or var obj = {}; Ques: 5 What looping structures are there in JavaScript? Ans: for, while, do-while loops, but no foreach. Ques: 6 How about 2+5+"8"? Ans: Since 2 and 5 are integers, this is number arithmetic, since 8 is a string, its concatenation, so 78 is the result. Ques: 7 What does "1"+2+4 evaluate to? Ans: Since 1 is a string, everything is a string, so the result is 124. Ques: 8 What boolean operators does JavaScript support? Ans: &&, || and ! Ques: 9 What is negative infinity? Ans: Its a number in JavaScript, derived by dividing negative number by zero. Ques: 10 How do you convert numbers between different bases in JavaScript? Ans: Use the parseInt() function, that takes a string as the first parameter, and the base as a second parameter. So to convert hexadecimal 3F to decimal, use parseInt ("3F", 16); What does isNaN function do? - Return true if the argument is not a number. Ques: 11 What are JavaScript types? Ans: Number, String, Boolean, Function, Object, Null, Undefined. Ques: 12 Whats relationship between JavaScript and ECMAScript? Ans: ECMAScript is yet another name for JavaScript (other names include LiveScript). The current JavaScript that you see supported in browsers is ECMAScript revision 3 Ques: 13 What does break and continue statements do? Ans: Continue statement continues the current loop (if label not specified) in a new iteration whereas break statement exits the current loop. Ques: 14 What does the delete operator do? Ans: The delete operator is used to delete all the variables and objects used in the program ,but it does not delete variables declared with var keyword. Ques: 15 What is === operator ? Ans: ==== is strict equality operator ,it returns true only when the two operands are having the same value without any type conversion. Ques: 16 What are undefined and undeclared variables? Ans: Undeclared variables are those that are not declared in the program (do not exist at all),trying to read their values gives runtime error.But if undeclared variables are assigned then implicit declaration is done .

Undefined variables are those that are not assigned any value but are declared in the program.Trying to read such variables gives special value called undefined value. Ques: 17 Does javascript have the concept level scope? Ans: No. Javascript does not have block level scope,all the variables declared inside a function possess the same level of scope unlike c,c++,java. Ques: 18 What is variable typing in javascript? Ans: It is perfectly legal to assign a number to a variable and then assign a string to the same variable as follows example i = 10; i = "string"; This is called variable typing Ques: 19 What is the difference between undefined value and null value? Ans: A. Undefined value cannot be explicitly stated that is there is no keyword called undefined whereas null value has keyword called null B. typeof undefined variable or property returns undefined whereas typeof null value returns object Ques: 20 What does undefined value mean in javascript? Ans: Undefined value means the variable used in the code doesnt exist or is not assigned any value or the property doesnt exist.

Javascript Interview Questions And Answers

Page 1
Tot Show al Post Your Answers Pos Answers ts Show Answers Post Your Answers

Questions

Last Post

JavaScript is developed by a. Brendan Eich b. Tim Duncan c. Bjarne Stroustrup d. Denish Richie JavaScript is widely used for a. server-side web development b. client-side web development c. both client-side and server-side web development JavaScript introduced by a. Microsoft b. IBM c. Google d. Sun Microsystem First name of JavaScript is a. Oak b. Mocha

vivek sharma

Show Answers

Post Your Answers

sonu

Show Answers Show Answers

Post Your Answers Post Your Answers

virender saini 05.02.09 Vivek

c. JScript d. JSL Using which tag we insert an JavaScript in HTML page? a. <JavaScript type="text/javascript"></JavaScript> Show b. <script Answers type="text/javascript"></script> c. <JScript type="text/javascript"></JScript> d. <HTMLScript type="text/javascript"></HTMLScript> JavaScript is case-sensitive or not?

Post Your Answers

varsha shukla

Show Answers

Post Your Answers

05.02.09 Vivek

Write syntax to get "R4R Welcomes you!" with using JavaScript? a. document.write("R4R Welcomes Show You!") Answers b. print("R4R Welcomes You!") c. print.write("R4R Welcomes You!") d. script.write("R4R Welcomes You!") We use <script></Script> tag within a. <head> Show b. <body> Answers c. <title> d. <JavaScript> Which popup box you use to verify something from user? Show a. alert("Write some text here") b. confirm("Write some text here") Answers c. prompt("Write here some text","Write default value here") Which popup box you use when want some information comes from user? a. alert("Write some text here") Show b. confirm("Write some text here") Answers c. prompt("Write here some text","Write default value here") Which popup box you use when want a value from user before open a page? a. alert("Write some text here") Show b. confirm("Write some text here") Answers c. prompt("Write here some text","Write default value here") ______ JavaScript is also called client-side JavaScript.

Post Your Answers

05.02.09 Vivek

Post Your Answers

23.07.10 kiran

Post Your Answers

05.02.09 Vivek

Post Your Answers

05.02.09 Vivek

Post Your Answers

23.06.10 vaishalee

Show Answers

1 1

Post Your Answers Post Your Answers

19.10.10 Aditya 19.10.10 Aditya

__________ JavaScript is also called Show server-side JavaScript. Answers A. Microsoft

B. Navigator C. LiveWire D. Native What are variables used for in JavaScript Programs? A. Storing numbers, dates, or other values Show B. Varying randomly Answers C. Causing high-school algebra flashbacks D. None of the above _____ JavaScript statements embedded in an HTML page can respond to user events such as mouse-clicks, form input, and page navigation. Show A. Client-side Answers B. Server-side C. Local D. Native What should appear at the very end of your JavaScript? The <script LANGUAGE="JavaScript">tag A. B. C. D. The </script> The <script> The END statement None of the above

Post Your Answers

19.10.10 Aditya

Post Your Answers

19.10.10 Aditya

Show Answers

Post Your Answers

shakeel

Which of the following can't be done with client-side JavaScript? A. Validating a form Show B. Sending a form's contents by Answers email C. Storing the form's contents to a database file on the server D. None of the above Which of the following are capabilities of functions in JavaScript? A. Return a value B. Accept parameters and Return a value C. Accept parameters D. None of the above

Post Your Answers

19.10.10 Aditya

Show Answers

Post Your Answers

ashish

How does JavaScript store dates in a Show date object?

Answers

Post Your Answers

19.10.10 Aditya

A. The number of milliseconds since January 1st, 1970 B. The number of days since January 1st, 1900 C. The number of seconds since Netscape's public stock offering. D. None of the above What is the correct JavaScript syntax to write "Hello World"? A. System.out.println("Hello World") B. println ("Hello World") C. document.write("Hello World") D. response.write("Hello World")

Show Answers

Post Your Answers

shakeel

Q1. What is JavaScript? Ans: JavaScript is a platform-independent,event-driven, interpreted client-side scripting and programming language developed by Netscape Communications Corp. and Sun Microsystems. Q2. How to read and write a file using javascript? Ans: I/O operations like reading or writing a file is not possible with client-side javascript. However , this can be done by coding a Java applet that reads files for the script. Q3. How to detect the operating system on the client machine? Ans: In order to detect the operating system on the client machine, the navigator.appVersion string (property) should be used. Q4. Where are cookies actually stored on the hard disk? Ans: This depends on the user's browser and OS. In the case of Netscape with Windows OS, all the cookies are stored in a single file called cookies.txt c:\Program Files\Netscape\Users\username\cookies.txt In the case of IE,each cookie is stored in a separate file namely username@website.txt. c:\Windows\Cookies\username@Website.txt Q5. What can javascript programs do? Ans: Generation of HTML pages on-the-fly without accessing the Web server. The user can be given control over the browser like User input validation Simple computations can be performed on the client's machine The user's browser, OS, screen size, etc. can be detected Date and Time Handling. Q6. How to set a HTML document's background color? Ans: document.bgcolor property can be set to any appropriate color. Q7. What is reason of the "Access is Denied" ? Ans: The "Access Denied" error in any browser is due to the following reason.

A javascript in one window or frame is tries to access another window or frame whose document's domain is different from the document containing the script. Q8. Is a javascript script faster than an ASP script? Ans: Yes. Since javascript is a client-side script it does require the web server's help for its computation,so it is always faster than any server-side script like ASP,PHP,etc. [an error occurred while processing this directive] Q9. Are Java and JavaScript the Same? Ans: No. java and javascript are two different languages. Java is a powerful object - oriented programming language like C++,C whereas Javascript is a client-side scripting language with some limitations. Q10. How to embed javascript in a web page? Ans: javascript code can be embedded in a web page between <script langugage="javascript"></script> tags

Você também pode gostar