Friday, November 8, 2013

HyperLink in Reapeater Control ASP.NET

Add a HyperLink to a  Reapeater Control  in ASP.NET


Place a Repeater control on a form.


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Repeater ID="Repeater1" runat="server">
        <HeaderTemplate>
        <table>
        <th>ID</th>
           <th>name</th>
              <th>marks</th>
        </HeaderTemplate>
        <ItemTemplate>
        <tr>
        <td>            <asp:Label ID="Label1" runat="server" Text='<%#Eval("rollno")%>'></asp:Label></td>

          <td> <%#Eval("name") %></td>
         <td>  <%#Eval("marks") %></td>
         <td>
             <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl ='<%#DataBinder.Eval(Container.DataItem,"rollno","show.aspx?id={0}")%>'>Go</asp:HyperLink></td>
       </tr> </ItemTemplate>
        </asp:Repeater>
    </div>
    </form>
</body>

</html>


Now Create a connect class


public class Connect
{
    SqlConnection con;
public Connect()
    {
     con   = new SqlConnection("Data Source=.;Initial Catalog=[DatabaseName];Integrated Security=True");
      
}

    public DataTable Select()
    {
        SqlDataAdapter ad = new SqlDataAdapter("select * from stud", con);
        DataSet ds = new DataSet();
        ad.Fill(ds, "stud");
        return ds.Tables[0];
    }
}


In the code behind

public partial class repeater : System.Web.UI.Page
{
    Connect c = new Connect();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            bind();
        }
    }

    private void bind()
    {
        
        Repeater1 .DataSource =c.Select();
        DataBind();
    }
}

Create another Webform named show.aspx

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <h1> </h1>
    </div>
    <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
    </form>
</body>
</html>

Just retrieve the Query string aand display it

public partial class show : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Label1.Text = "RollNo: " + Request.QueryString["id"];
    }
}




If you want you can provide more styles to repeater. Enjoy!!!

Adding checkbox in Gridview

Gridview CheckBox


In a form place a Gridview and edit columns. In the TemplateField add a CheckBox.
Add BoundFileds to connect to database values. My table is as follows






 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
        BackColor="White" BorderColor="#999999" BorderStyle="None" BorderWidth="1px" 
        CellPadding="3" GridLines="Vertical"   DataKeyNames="rollno">
        <AlternatingRowStyle BackColor="#DCDCDC" />
        <Columns>
            <asp:TemplateField HeaderText="select">
                             <ItemTemplate>
                    <asp:CheckBox ID="chklist" runat="server" />
                </ItemTemplate>
            </asp:TemplateField>
            <asp:BoundField DataField="rollno" HeaderText="ID" />
            <asp:BoundField DataField="name" HeaderText="Name" />
            <asp:BoundField DataField="marks" HeaderText="Marks" />
        </Columns>
        <FooterStyle BackColor="#CCCCCC" ForeColor="Black" />
        <HeaderStyle BackColor="#000084" Font-Bold="True" ForeColor="White" />
        <PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
        <RowStyle BackColor="#EEEEEE" ForeColor="Black" />
        <SelectedRowStyle BackColor="#008A8C" Font-Bold="True" ForeColor="White" />
        <SortedAscendingCellStyle BackColor="#F1F1F1" />
        <SortedAscendingHeaderStyle BackColor="#0000A9" />
        <SortedDescendingCellStyle BackColor="#CAC9C9" />
        <SortedDescendingHeaderStyle BackColor="#000065" />
    </asp:GridView>
    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Select" 
        Height="26px" />
    <p>
        <asp:Literal ID="Literal1" runat="server"></asp:Literal>
    </p>
    <asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False"  DataKeyNames="rollno">
        <Columns>
            <asp:TemplateField>
                <EditItemTemplate>
                    <asp:CheckBox ID="CheckBox1" runat="server" />
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:CheckBox ID="CheckBox1" runat="server" />
                </ItemTemplate>
            </asp:TemplateField>
            <asp:BoundField DataField="rollno" HeaderText="RollNo" />
            <asp:BoundField DataField="name" HeaderText="name" />
            <asp:BoundField DataField="marks" HeaderText="Mark" />
            <asp:CommandField ShowEditButton="True" />
        </Columns>
    </asp:GridView>

Create a Connect Class

using System.Data.SqlClient;
using System.Data;
public class Connect
{
    SqlConnection con;
public Connect()
    {
     con   = new SqlConnection(@"Data Source=.;Initial Catalog=[Dbname];Integrated Security=True");
      
}

    public DataTable Select()
    {
        SqlDataAdapter ad = new SqlDataAdapter("select * from stud", con);
        DataSet ds = new DataSet();
        ad.Fill(ds, "stud");
        return ds.Tables[0];
    }
}


Now In the code behind  create the following code



public partial class _Default : System.Web.UI.Page
{
    Connect c = new Connect();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            bind();
        }
    }

    private void bind()
    {

        GridView1.DataSource = c.Select();
        DataBind();
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        string str = string.Empty;
        string name = ""; 
        foreach (GridViewRow gr in GridView1.Rows)
        {
            CheckBox ck = (CheckBox)gr.FindControl("chklist");
            if (ck != null && ck.Checked )
            {
                str += GridView1.DataKeys[gr.RowIndex].Value.ToString() + "  ";
                name += gr.Cells[2].Text+"  ";
            }
        }
        Literal1.Text ="selected:"+ str + "<br/>" + name;
    }

}


Now Save and Run the program


Enjoy!!

Monday, July 22, 2013

Regular Expressiona in c#

Regular Expressions

A regular expression is a set of characters that can be compared to a string to determine whether the string meets specified format requirements. You can also use regular expressions to extract portions of the text or to replace text.

Which uses the System.Text.RegularExpressions namespace, performs this check using the static method System. Text.RegularExpressions.Regex.IsMatch method

How to Use Regular Expressions for Pattern Matching
Example:-
“^\d{5}$” => means that the string must be exactly five numeric digits.
"^" => Match beginning of input
"\d" => Match only numeric digits
"{5}" => Match exactly 5 characters
"$" => Match end of input

Regular expressions can be used to match complex input patterns, too.

Regular expressions are an extremely efficient way to check user input,
However, Regular expressions are difficult to create unless you are extremely familiar with the format.

"\d" => "[0-9]" => Matches a digit character. 
"\d{3}" => "[0-9]{3} => Matches 3 digit character. 
(< 3 and > 3 are Invalid)
"\d{2,5}" => "[0-9]{2,5} => Matches 1 to 5 digit character
(< 2 and >5 are Invalid)
"\D" => "[^0-9]" => Matches a non digit character.
"\s" => "[\f\n\r\t\v]" => Matches any white-space character.
(Space, Tab and form-feed)
"\S" => "[^\f\n\r\t\v]" => Matches any non-white-space character.
"\w" => "[A-Za-z0-9]" => Matches any word character including underscore.
"\W" => "[^A-Za-z0-9]" => Matches any non word character, including underscore.


How to Extract Matched Data

Besides simply determining whether a string matches a pattern, you can extract information from a string. For example, if you are processing a text file that contains “CompanyName: Contoso, Inc.”, you could extract just the company name using a regular expression.

To match a pattern and capture the match, follow these steps:

1. Create a regular expression, and enclose in parentheses the pattern to be matched.
2. Create an instance of the System.Text.RegularExpressions.Match class using the static Regex. Match method.
3. Retrieve the matched data by accessing the elements of the Match. Groups array.

EXAMPLE 1

 string input = "Company Name: Contoso, Inc.";
              Match m = Regex.Match(input, @"Company Name: (.*$)");
           MessageBox.Show (m.Groups[1].ToString());
   
EXAMPLE 2
Email Phone number validation 

 Regex r = new Regex(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");
          
            Regex r2=new Regex( @"^\d{4}(\-\d{7})?$");

            // @"^\(?(\d{3})\)?[\s\-]?(\d{3})\-?(\d{4})$");  international code 
            if (r.IsMatch(txtMail.Text))
            {
                MessageBox.Show("Valid");
            }

               
            else
            {
                MessageBox.Show("Invalid Email");
            }

             if(r2.IsMatch(textBoxPhNo.Text))
            {
                MessageBox.Show("Valid");
            }

               
            else
            {
                MessageBox.Show("Invalid phone number");

            }


EXAMPLE 3

3 DIGIT NUMBER VALIDATION

Regex x = new Regex(@"^[0-9]{1,3}$");
           // Regex x = new Regex(@"^\d{3}$");

            if (x.IsMatch(txtNo.Text))
            {
                MessageBox.Show("Valid");
            }


            else
            {
                MessageBox.Show("Invalid");

            }
Summary

■ Regular expressions enable you to determine whether text matches almost any type of format. Regular expressions support dozens of special characters and operators. The most commonly used are “^” to match the beginning of a string, “$” to match the end of a string, “?” to make a character optional, “.” to match any character, and “*” to match a repeated character.

■ To match data using a regular expression, create a pattern using groups to specify the data you need to extract, call Regex .Match to create a Match object, and then examine each of the items in the Match. Groups array.

Sunday, June 23, 2013

LINQ

Language Integrated Query (LINQ)



LINQ is a programming model that is the composition of general-purpose standard query operators that allow you to work with data, regardless of the data source in any .NET based programming language. It is the name given to a set of technologies based on the integration of query capabilities into any .NET language.

What are the three main components of LINQ or Language INtegrated Query?

1. Standard Query Operators
2. Language Extensions
3. LINQ Providers

How are Standard Query Operators implemented in LINQ?

Standard Query Operators are implemented as extension methods in .NET Framework. These Standard Query Operators can be used to work with any collection of objects that implements the IEnumerable interface. A class that inherits from the IEnumerable interface must provide an enumerator for iterating over a collection of a specific type. All arrays implement IEnumerable. Also, most of the generic collection classes implement IEnumerable interface.

How are Standard Query Operators useful in LINQ?

Standard Query Operators in LINQ can be used for working with collections for any of the following and more.
1. Get total count of elements in a collection.
2. Order the results of a collection.
3. Grouping.
4. Computing average.
5. Joining two collections based on matching keys.
6. Filter the results


List the important language extensions made in C# to make LINQ a reality?

1. Implicitly Typed Variables
2. Anonymous Types
3. Object Initializers
4. Lambda Expressions

What is the purpose of LINQ Providers in LINQ?

LINQ Providers are a set of classes that takes a LINQ query and dynamically generates a method that executes an equivalent query against a specific data source.


What are the four LINQ Providers that .NET Framework ships?

1. LINQ to Objects - Executes a LINQ query against a collection of objects
2. LINQ to XML - Executes an XPATH query against XML documents
3. LINQ to SQL - Executes LINQ queries against Microsoft SQL Server.
4. LINQ to DataSets - Executes LINQ queries against ADO.NET DataSets.

What are the advantages of LINQ over Stored Procedures?

Below is the three advantages of LINQ over stored procedures.

Debugging - As debug point concern, as LINQ is part of .NET, we can use the visual studio's debugger to debug the queries but it is tough to debug the Stored procedure as it will not support the visual studio debugger.

Deployment - In case of deployment, we need to provide an additional script for stored procedures to execute but in case of LINQ, it will complie into single DLL hence deployment becomes easier.

Type Safety - As LINQ is type safe, the queries errors are type checked at compile time. Better suggest to use LINQ because it helps to encounter an error at the compile time rather than at 
runtime exception.

What is the difference between FirstOrDefault() and SingleOrDefault() extension method in LINQ

FirstOrDefault() = gets the first item that matches a given criteria.
SingleOrDefault() = if you specify this extension method that means you are specifically saying that there can be only one value that matches the criteria. If there are more then 1 value that matches the criteria, throw an exception. 

What is the disadvantage of LINQ over stored procedures?

The disadvantage with LINQ is, it is not a precompiled statement where as stored procedures are precompiled. In case of LINQ the queries need to be compile before the execution. So according to this, stored procedures are faster in performance as compared to LINQ

What is the difference between First() and Single() extension methods in LINQ ?

• First() - There is at least one result, an exception is thrown if no result is returned.

• Single() - There is exactly 1 result, no more, no less, an exception is thrown if no result is returned. 

 What is the DataContext class and how is it related to LINQ?

After you add a LINQ to SQL Classes item to a project and open the O/R Designer, the empty design surface represents an empty DataContext class ready to be configured. The DataContext class is a LINQ to SQL class that acts as a conduit between a SQL Server database and the LINQ to SQL entity classes mapped to that database. This class contains the connection string information and the methods for connecting to a database and manipulating the data in the database. It is configured with connection information provided by the first item that is dragged onto the design surface.


Write a program using LINQ to find the sum of first 5 prime numbers?






Wednesday, March 27, 2013

javascript in ASP.NET

learn javascript in asp.net

Introduction


  • de facto standard for client-side Web development
  • Enable to build robust applications in combination with ASP.NET
  • Mainly used to compensate limitations of ASP.NET  in terms of usage of custom controls
  • JavaScript can allow you to create new things on your website that are both dynamic and interactive, allowing you to do things like find out some information about a user (like monitor resolution and browser), check that forms have been filled in correctly, rotate images, make random text, do calculations and many other things.
Inserting JavaScript into an ASP.NET Page



Steps:

  • Define the script block that contains the JavaScript function. 
  • Insert the script block programmatically:using the Page.RegisterStartupScript() or the Page.RegisterClientScriptBlock() method. 

Adding JavaScript to a Server Control

Illustrating with the help of a real world example. 

Button control in ASP.NET to generate the current time:
Button1.Value = DateTime.Now.ToString();

Note:ASP.NET page here gets the time from the server that generated the page. 

What if you wanted the button to show the time of the person viewing the page? The easiest way of accomplishing this task would be to do this using JavaScript on the client-side.

<%@ Page Language="C#" %>
<script runat="server">
    void Button1_Click(object sender, EventArgs e) 
    {
      Response.Write("Postback!");
   }
 </script>
<html>
<head> </head>
<body onload="javascript:document.forms[0]['Button1'].value=Date();">
    <form runat="server">
        <p>
            <asp:Button id="Button1" onclick="Button1_Click" 
             runat="server" Font-Bold="True" Font-Names="Verdana"
             Font-Size="Larger"></asp:Button>
        </p>
    </form>
</body>
</html>


Button showing the current time: 









Performing a Simple Button-rollover

Hover mouse over a button
Useful for Web pages that have multiple buttons
Code:

<%@ Page Language="C#" %>
<script runat="server">    
    void ImageButton1_Click(object sender, ImageClickEventArgs e)    
   {
       Label1.Text = "Postback!";
    }
</script>

<html>
<head></head>
<body>
    <form runat="server">
        <p>
          <asp:ImageButton id="ImageButton1” onmouseover="this.src='button2.jpg‘ " 
             onclick="ImageButton1_Click“ onmouseout="this.src='button1.jpg‘ " 
             runat="server“ ImageUrl="button1.jpg"></asp:ImageButton>
        </p>
        <p>
            <asp:Label id="Label1" runat="server" />
        </p>
    </form>
</body>
</html>

Setting Control Focus

Seting focus on particular control
//to set focus on first textbox when there are multipile textboxes on a web page

<body onload="document.forms[0]['TextBox1'].focus();">

Changing the Control Focus Dynamically

Turn the <body> tag into a HTML server control
<body id="Body1" runat="server">

Placing  code constructs in ASP.NET server-side events.

Body1.Attributes["onload"] = “document.forms[0][‘TextBox2’].focus();";

Keeping JavaScript in a Separate File (.js)

It is highly recommended to keep javascript in a seperate file.
Code to include .js file in ASP.NET  page:

Page.RegisterClientScriptBlock("MyScript",
   "<script language=javascript src='MyJavaScriptFile.js'>");



JavaScript Tutorial

Javascript online tutorial
Javascript tutorial

JavaScript Introduction

JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer, Firefox, Chrome, Opera, and Safari.

Definition of JavaScript

JavaScript was designed to add interactivity to HTML pages
JavaScript is a scripting language
A scripting language is a lightweight programming language
JavaScript is usually embedded directly into HTML pages
JavaScript is an interpreted language (means that scripts execute without preliminary compilation)
Everyone can use JavaScript without purchasing a license

Java and JavaScript are two completely different languages in both concept and design!

Java (developed by Sun Microsystems) is a powerful and much more complex programming language - in the same category as C and C++.

The scope of  JavaScript 

JavaScript gives HTML designers a programming tool - HTML authors are normally not programmers, but JavaScript is a scripting language with a very simple syntax! Almost anyone can put small "snippets" of code into their HTML pages

JavaScript can put dynamic text into an HTML page - A JavaScript statement like this: 
document.write("<h1>" + name + "</h1>") ;
can write a variable text into an HTML page

• JavaScript can react to events - A JavaScript can be set to execute when something happens, like when a page has finished loading or when a user clicks on an HTML element

 JavaScript can read and write HTML elements - A JavaScript can read and change the content of an HTML element

• JavaScript can be used to validate data - A JavaScript can be used to validate form data before it is submitted to a server. This saves the server from extra processing

• JavaScript can be used to detect the visitor's browser - A JavaScript can be used to detect the visitor's browser, and - depending on the browser - load another page specifically designed for that browser

• JavaScript can be used to create cookies - A JavaScript can be used to store and retrieve information on the visitor's computer

Example 1

<html>
<body>

<h1>My First Web Page</h1>


<script type="text/javascript">

document.write("<p>" + Date() + "</p>");
</script>

</body>

</html>


Example 2

<html>
<body>

<h1>My First Web Page</h1>


<p id="demo"></p>


<script type="text/javascript">

document.getElementById("demo").innerHTML=Date();
</script>

</body>

</html> 

Example 3

<html> 
<head>
<script type="text/javascript">
function displayDate()
{
document.getElementById("demo").innerHTML=Date();
}
</script>
</head>
<body>
<h1>My First Web Page</h1>
<p id="demo"></p>
<button type="button" onclick="displayDate()">Display Date</button>
</body>
</html> 


Scripts in <head> and <body>

You can place an unlimited number of scripts in your document, and you can have scripts in both the body and the head section at the same time.
It is a common practice to put all functions in the head section, or at the bottom of the page. This way they are all in one place and do not interfere with page content.
Using an External JavaScript
JavaScript can also be placed in external files. 
External JavaScript files often contain code to be used on several different web pages. 
External JavaScript files have the file extension .js.
Note: External script cannot contain the <script></script> tags!
To use an external script, point to the .js file in the "src" attribute of the <script> tag:

Example

<html>
<head>
<script type="text/javascript" src="xxx.js"></script>
</head>
<body>
</body>
</html>

JavaScript is Case Sensitive

Unlike HTML, JavaScript is case sensitive - therefore watch your capitalization closely when you write JavaScript statements, create or call variables, objects and functions.

Example 

<script type="text/javascript">
document.write("<h1>This is a heading</h1>");
document.write("<p>This is a paragraph.</p>");
document.write("<p>This is another paragraph.</p>");
</script> 

JavaScript Comments

Single line comments start with //.
Multi line comments start with /* and end with */.

JavaScript Variables

JavaScript variables are used to hold values or expressions.
A variable can have a short name, like x, or a more descriptive name, like carname.
Rules for JavaScript variable names:
Variable names are case sensitive (y and Y are two different variables)
Variable names must begin with a letter or the underscore character.

Example 

<html>
<body>
<script type="text/javascript">
var firstname;
firstname="Hege";
document.write(firstname);
document.write("<br />");
firstname="Tove";
document.write(firstname);
</script>
<p>The script above declares a variable,assigns a value to it, displays the value, changes the value,and displays the value again.</p>
</body>
</html>

JavaScript Arithmetic Operators

Operator Description

+ Addition
- Subtraction
* Multiplication
/ Division
%       Modulus (division remainder)
++ Increment
-- Decrement


JavaScript Assignment Operators

Operator Example

= x=y  
+= x+=y
-=  x-=y
*=             x*=y
/= x/=y
%= x%=y

The + Operator Used on Strings

The + operator can also be used to add string variables or text values together.
To add two or more string variables together, use the + operator.
Example
txt1="What a very";
txt2="nice day";
txt3=txt1+txt2;
Adding Strings and Numbers

The rule is: If you add a number and a string, the result will be a string!

Example

x=5+5;
document.write(x);

x="5"+"5";

document.write(x);

x=5+"5";

document.write(x);

x="5"+5;

document.write(x); 

Comparison Operators

Operator Description

== is equal to 
===    is exactly equal to (value and type)
!=       is not equal
> is greater than
<       is less than
>= is greater than or equal to
<= is less than or equal to

Logical Operators

Operator Description

&& and
|| or
! not

Conditional Operator

Syntax

variablename=(condition)?value1:value2 

Example

greeting=(visitor=="PRES")?"Dear President ":"Dear ";


Conditional Statements
In JavaScript we have the following conditional statements:
if statement - use this statement to execute some code only if a specified condition is true
if...else statement - use this statement to execute some code if the condition is true and another code if the condition is false
if...else if....else statement - use this statement to select one of many blocks of code to be executed
switch statement - use this statement to select one of many blocks of code to be executed


If Statement

Syntax

if (condition)
  {
  code to be executed if condition is true
  }

Example

<script type="text/javascript">
//Write a "Good morning" greeting if
//the time is less than 10

var d=new Date();

var time=d.getHours();

if (time<10)

  {
  document.write("<b>Good morning</b>");
  }
</script>

If...else Statement

Syntax

if (condition)
  {
  code to be executed if condition is true
  }
else
  {
  code to be executed if condition is not true
  }

Example

<script type="text/javascript">
//If the time is less than 10, you will get a "Good morning" greeting.
//Otherwise you will get a "Good day" greeting.

var d = new Date();

var time = d.getHours();

if (time < 10)

  {
  document.write("Good morning!");
  }
else
  {
  document.write("Good day!");
  }
</script>

If...else if...else Statement

Syntax

if (condition1)
  {
  code to be executed if condition1 is true
  }
else if (condition2)
  {
  code to be executed if condition2 is true
  }
else
  {
  code to be executed if neither condition1 nor condition2 is true
  }

Example  

<script type="text/javascript">
var d = new Date()
var time = d.getHours()
if (time<10)
  {
  document.write("<b>Good morning</b>");
  }
else if (time>10 && time<16)
  {
  document.write("<b>Good day</b>");
  }
else
  {
  document.write("<b>Hello World!</b>");
  }
</script>

The JavaScript Switch Statement

Used in the place of multiple if statements.

 Syntax

switch(n)
{
case 1:
  execute code block 1
  break;
case 2:
  execute code block 2
  break;
default:
  code to be executed if n is different from case 1 and 2
}


Example  


<script type="text/javascript">
//You will receive a different greeting based
//on what day it is. Note that Sunday=0,
//Monday=1, Tuesday=2, etc.

var d=new Date();

var theDay=d.getDay();
switch (theDay)
{
case 5:
  document.write("Finally Friday");
  break;
case 6:
  document.write("Super Saturday");
  break;
case 0:
  document.write("Sleepy Sunday");
  break;
default:
  document.write("I'm looking forward to this weekend!");
}
</script>

JavaScript Popup Boxes

JavaScript has three kind of popup boxes: Alert box, Confirm box, and Prompt box.

Alert Box

An alert box is often used if you want to make sure information comes through to the user.
When an alert box pops up, the user will have to click "OK" to proceed. 

Syntax

alert("sometext");

Example

<html>
<head>
<script type="text/javascript">
function show_alert()
{
alert("I am an alert box!");
}
</script>
</head>
<body>
<input type="button" onclick="show_alert()" value="Show alert box" />
</body>
</html>

Confirm Box

A confirm box is often used if you want the user to verify or accept something.
When a confirm box pops up, the user will have to click either "OK" or "Cancel" to proceed. 
If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box returns false.

Syntax

confirm("sometext");

Example

<html>
<head>
<script type="text/javascript">
function show_confirm()
{
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_confirm()" value="Show confirm box" />


</body>

</html>


Prompt Box

A prompt box is often used if you want the user to input a value before entering a page.
When a prompt box pops up, the user will have to click either "OK" or "Cancel" to proceed after entering an input value. 
If the user clicks "OK" the box returns the input value. If the user clicks "Cancel" the box returns null.

Syntax

prompt("sometext","defaultvalue");

Example

<html>
<head>
<script type="text/javascript">
function show_prompt()
{
var name=prompt("Please enter your name","Harry Potter");
if (name!=null && name!="")
  {
  document.write("Hello " + name + "! How are you today?");
  }
}
</script>
</head>
<body>

<input type="button" onclick="show_prompt()" value="Show prompt box" />

</body>
</html>


JavaScript Loops

In JavaScript, there are two different kind of loops:

for -      loops through a block of code a specified number of times
while - loops through a block of code while a specified condition is true

Syntax

for (variable=startvalue;variable<=endvalue;variable=variable+increment)
{
code to be executed
}

Example

<html>
<body>
<script type="text/javascript">
var i=0;
for (i=0;i<=5;i++)
{
document.write("The number is " + i);
document.write("<br />");
}
</script>
</body>
</html>

The while Loop

The while loop loops through a block of code while a specified condition is true.

Syntax

while (variable<=endvalue)
  {
  code to be executed
  }

Example

<html>
<body>
<script type="text/javascript">
var i=0;
while (i<=5)
  {
  document.write("The number is " + i);
  document.write("<br />");
  i++;
  }
</script>
</body>
</html>

The do...while Loop

The do...while loop is a variant of the while loop. This loop will execute the block of code ONCE, and then it will repeat the loop as long as the specified condition is true.

Syntax

do
  {
  code to be executed
  }
while (variable<=endvalue);

Example

<html>
<body>
<script type="text/javascript">
var i=0;
do
  {
  document.write("The number is " + i);
  document.write("<br />");
  i++;
  }
while (i<=5);
</script>
</body>
</html>

The break Statement

The break statement will break the loop and continue executing the code that follows after the loop (if any).

Example

<html>
<body>
<script type="text/javascript">
var i=0;
for (i=0;i<=10;i++)
  {
  if (i==3)
    {
    break;
    }
  document.write("The number is " + i);
  document.write("<br />");
  }
</script>
</body>
</html>

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==3)
    {
    continue;
    }
  document.write("The number is " + i);
  document.write("<br />");
  }
</script>
</body>
</html>

Hope you enjoyed.. Happy Programming