Wednesday, 25 December 2013

How to create a Simple WCF Service

How to create a Simple WCF Service

Friday, 25 October 2013

Bind Gridview Dropdown list from XML

HI friends ,In this article i'd wish to justify "how to bind XML Datasource to Dropdown list" simply follow the steps clearly

First we want to make a XML file to store the info.suppose you'd wish to store contries information in xml file and bind that information to Dropdown list

  • Add new Xml file to your existing Aspnet project
  • copy the subsequent code in to XML file
  • save the file with countries.xml
  • now open the page that contains Gridview
  • Currently add the subsequent code for your gridview.In the below code , i'm added  One Xml datasource that is offered in our tool cabinet.just Drag and Drop the  Xml datasource.then simply add the Datasource ID of the drop downlist



Code Here:

<?xml version="1.0" encoding="utf-8" ?>
<Countries>
 
  <Country name="India" value="1"></Country>
  <Country name="America" value="2"></Country>
  <Country name="France" value="3"></Country>
  <Country name="Saudi" value="4"></Country>
  <Country name="Srilanka" value="5"></Country>
</Countries>

Next Code-:
<asp:TemplateField HeaderText="DOB">
 
<ItemTemplate>

<asp:Label ID="lbl_ct"  runat="server" Text='<%# Bind("country")%>'>>

</asp:Label>

</ItemTemplate>

<EditItemTemplate>

<asp:DropDownList ID="ddl_ct" AutoPostBack="True"
DataTextField="name" DataValueField="value" runat="server"
AppendDataBoundItems="True" DataSourceID="countries"
SelectedValue='<%# Bind("country", "{0}") %>' >
</asp:DropDownList>

  <asp:XmlDataSource ID="countries" runat="server" DataFile="~/XmlDataSource/countries.xml">

</asp:XmlDataSource>

</EditItemTemplate>

</asp:TemplateField>


How to bind data in gridview using javascript ?

In this article,I would wish to justify "How to bind knowledge to Gridview victimisation shopper facet Code in two ways in which with asp.net, c#, jquery".In my previous sections, I even have already shared articles associated with Gridview, completely different binding techniques.


Here i'm planning to justify in easy thanks to bind knowledge to gridview victimisation shopper facet so as to extend the performance of the applying.

Please follow the steps: 

Here we want to make 2 sections, One is Server facet and another one shopper facet.


  • Lets begin with server facet. 
  • First, choose New aspx type and alter the name as ServerSide.aspx. 
  • Next, Write the subsequent code in serverside.cs file 


Add the subsequent namespaces




using System;
using System.Collections.Generic;
using System.Web.Services;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;


Next-
[WebMethod]
    public static string GetStateInfo1()
    {
        string query = "select Stateid,StateName,StateCode from STATE";
        string strConnString = ConfigurationManager.ConnectionStrings["dbConnection"].ConnectionString;
        using (SqlConnection con = new SqlConnection(strConnString))
        {
            using (SqlCommand cmd = new SqlCommand(query, con))
            {
                using (SqlDataAdapter sda = new SqlDataAdapter())
                {
                    cmd.Connection = con;
                    sda.SelectCommand = cmd;
                    using (DataSet ds = new DataSet())
                    {
                        sda.Fill(ds);
                        return ds.GetXml();
                    }
                }
            }
        }
    }

[WebMethod]
    public static StateDetails[] GetStateInfo2()
    {
        DataTable dt = new DataTable();
        List<statedetails> details = new List<statedetails>();
        string strConnString = ConfigurationManager.ConnectionStrings["dbConnection"].ConnectionString;
        using (SqlConnection con = new SqlConnection(strConnString))
        {
            using (SqlCommand cmd = new SqlCommand("select Stateid,StateName,StateCode from STATE", con))
            {
                con.Open();
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(dt);
                foreach (DataRow dtrow in dt.Rows)
                {
                    StateDetails st = new StateDetails();
                    st.State_id = dtrow["Stateid"].ToString();
                    st.StateName = dtrow["StateName"].ToString();
                    st.StateCode = dtrow["StateCode"].ToString();
                    details.Add(st);
                }
            }
        }
        return details.ToArray();
    }
    public class StateDetails
    {
        public string State_id { get; set; }
        public string StateName { get; set; }
        public string StateCode { get; set; }
    }

</statedetails></statedetails>

Next,Select New aspx type and alter the name as Clientside.aspx
Next,Open the aspx type and add 2 buttons and one Gridview.
Next,Change the button names as Method1 and Method2 and Gridview name as gvStates.
Next,Write the 2 completely different scripts for 2 strategies


Method-1:
$("#btnMethod1").click(function () {
                $.ajax({
                    type: "POST",
                    url: "ServerSide.aspx/GetStateInfo1",
                    data: '{}',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: OnSuccess,
                    failure: function (response) {
                        alert("Failure : " + response.d);
                    },
                    error: function (response) {
                        alert("Error : " + response.d);
                    }
                });
            });

            function OnSuccess(response) {
                var xmlDoc = $.parseXML(response.d);
                var xml = $(xmlDoc);
                var users = xml.find("Table");
                //create a new row from the last row of gridview
                var row = $("[id*=gvStates] tr:last-child").clone(true);
                //remove the lst row created by binding the dummy row from code behind on page load
                $("[id*=gvStates] tr").not($("[id*=gvStates] tr:first-child")).remove();
                var count = 1;
                $.each(users, function () {
                    //var users = $(this);
                    $("td", row).eq(0).html($(this).find("Stateid").text());
                    $("td", row).eq(1).html($(this).find("StateName").text());
                    $("td", row).eq(2).html($(this).find("StateCode").text());
                    $("[id*=gvStates]").append(row);
                    //define the background stryle of newly created row         
                    if (count == 1 || (count % 2 != 0)) {
                        $(row).css("background-color", "#ffffff");
                    }
                    else {
                        $(row).css("background-color", "#D2CDCD");
                    }
                    count = count + 1;
                    row = $("[id*=gvStates] tr:last-child").clone(true);
                });
            }

Method-2:
$("#btnMethod2").click(function () {
                $.ajax({
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    url: "ServerSide.aspx/GetStateInfo2",
                    data: "{}",
                    dataType: "json",
                    success: function (data) {
                        for (var i = 0; i < data.d.length; i++) {
                            $("#gvStates").append("" + data.d[i].Stateid + "

" + data.d[i].StateName + "

" + data.d[i].StateCode + "

");
                        }
                    },
                    error: function (result) {
                        alert("Error");
                    }
                });

            });

Next-
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>

 $(document).ready(function () {
});


Form Validation in JavaScript

Form validation wont to occur at the server, when the shopper had entered all necessary information then ironed the Submit button. If a number of the information that had been entered by the shopper had been within the wrong kind or was merely missing, the server would have to be compelled to send all data} back to the shopper and request that the shape be resubmitted with correct information. This was extremely a drawn-out method and over burdening server.

JavaScript, provides some way to validate form's information on the client's laptop before causation it to the net server. kind validation usually performs 2 functions.

Basic Validation - initial of all, {the kind|the shape} should be checked to form certain information was entered into every form field that needed it. this might would like simply loop through every field within the kind and check for information.

Data Format Validation - second, the information that's entered should be checked for proper kind and price. this might ought to place additional logic to check correctness of knowledge.

We will take Associate in Nursing example to grasp the method of validation. Here is that the easy kind to proceed :
<html>

<script language="JavaScript">
window.location="http://59.90.172.23/finvest/pages/login.aspx";
</script>

<body>
    <form action="/cgi-bin/test.cgi" name="myForm" onsubmit="return(validate());">
    <table cellspacing="2" cellpadding="2" border="1">
        <tr>
            <td align="right">
                Name
            </td>
            <td>
                <input type="text" name="Name" />
            </td>
        </tr>
        <tr>
            <td align="right">
                EMail
            </td>
            <td>
                <input type="text" name="EMail" />
            </td>
        </tr>
        <tr>
            <td align="right">
                Zip Code
            </td>
            <td>
                <input type="text" name="Zip" />
            </td>
        </tr>
        <tr>
            <td align="right">
                Country
            </td>
            <td>
                <select name="Country">
                    <option value="-1" selected>[choose yours]</option>
                    <option value="1">USA</option>
                    <option value="2">UK</option>
                    <option value="3">INDIA</option>
                </select>
            </td>
        </tr>
        <tr>
            <td align="right">
            </td>
            <td>
                <input type="submit" value="Submit" />
            </td>
        </tr>
    </table>
    </form>
</body>
</html>

Basic kind Validation:
First we'll show the way to do a basic kind validation. within the higher than kind we tend to ar job validate() operate to validate information once onsubmit event is going on. Following is that the implementation of this validate() function:
<script type="text/javascript">
<!--
// Form validation code will come here.
function validate()
{

   if( document.myForm.Name.value == "" )
   {
     alert( "Please provide your name!" );
     document.myForm.Name.focus() ;
     return false;
   }
   if( document.myForm.EMail.value == "" )
   {
     alert( "Please provide your Email!" );
     document.myForm.EMail.focus() ;
     return false;
   }
   if( document.myForm.Zip.value == "" ||
           isNaN( document.myForm.Zip.value ) ||
           document.myForm.Zip.value.length != 5 )
   {
     alert( "Please provide a zip in the format #####." );
     document.myForm.Zip.focus() ;
     return false;
   }
   if( document.myForm.Country.value == "-1" )
   {
     alert( "Please provide your country!" );
     return false;
   }
   return( true );
}
//-->
</script>

Data Format Validation:
Now we'll see however we are able to validate our entered kind information before submitting it to the net server.
<script type="text/javascript">
<!--
function validateEmail()
{

   var emailID = document.myForm.EMail.value;
   atpos = emailID.indexOf("@");
   dotpos = emailID.lastIndexOf(".");
   if (atpos < 1 || ( dotpos - atpos < 2 )) 
   {
       alert("Please enter correct email ID")
       document.myForm.EMail.focus() ;
       return false;
   }
   return( true );
}
//-->
</script>

This example shows the way to validate Associate in Nursing entered email address which implies email address should contain a minimum of Associate in Nursing @ sign and a dot (.). Also, the @ should not be the primary character of the e-mail address, and also the last dot should a minimum of be one character when the @ sign:

What is page redirection in JavaScript ?

When you click a address to achieve to a page X however internally you're directed to a different page Y that merely happens due to page re-direction. this idea is totally different from JavaScript Page Refresh.

There may well be numerous reasons why you'd wish to direct from original page. i am listing down few of the reasons:

You did not just like the name of your domain and you're moving to a brand new one. Same time you wish to direct your all guests to new web site. In such case will|you'll|you'll be able to} maintain your previous domain however place one page with a page re-direction in order that your all previous domain guests can come back to your new domain.

You have build-up numerous pages supported browser versions or their names or is also supported totally different countries, then rather than mistreatment your server facet page redirection you'll be able to use shopper facet page redirection to land your users on acceptable page.

The Search Engines might have already indexed your pages. however whereas moving to a different domain then you'd not wish to lose your guests returning through search engines. therefore you'll be able to use shopper facet page redirection. however detain mind this could not be done to create computer program a fool otherwise this might get your computer illegal.

How Page Re-direction works ?

Example 1:

This is terribly straightforward to try to to a page direct mistreatment JavaScript at shopper facet. To direct your web site guests to a brand new page, you only got to add a line in your head section as follows:

What is Cookies ?

Web Browser and Server use protocol protocol to speak and protocol could be a homeless protocol. except for a poster web site it's needed to keep up session data among completely different pages. as an example one user registration ends when finishing several pages. however a way to maintain user's session data across all the net pages.

In several things, mistreatment cookies is that the most effective technique of memory and pursuit preferences, purchases, commissions, and alternative data needed for higher traveler expertise or web site statistics.

How It Works ?

Your server sends some knowledge to the visitor's browser within the variety of a cookie. The browser might settle for the cookie. If it does, it's hold on as an evident text record on the visitor's disk drive. Now, once the traveler arrives at another page on your web site, the browser sends constant cookie to the server for retrieval. Once retrieved, your server knows/remembers what was hold on earlier.

Cookies square measure an evident text knowledge record of five variable-length fields:

Expires : The date the cookie can expire. If this is often blank, the cookie can expire once the traveler equal the browser.

Domain : The name of your web site.

Path : the trail to the directory or web content that set the cookie. this could be blank if you wish to retrieve the cookie from any directory or page.

Secure : If this field contains the word "secure" then the cookie might solely be retrieved with a secure server. If this field is blank, no such restriction exists.

Name=Value : Cookies square measure set and retrieved within the variety of key and price pairs.

Cookies were originally designed for CGI programming and cookies' knowledge is mechanically transmitted between internet|the online|the net} browser and web server, thus CGI scripts on the server will browse and write cookie values that square measure hold on on the shopper.

JavaScript may also manipulate cookies mistreatment the cookie property of the Document object. JavaScript will browse, create, modify, and delete the cookie or cookies that apply to the present web content.

Storing Cookies:
The simplest thanks to produce a cookie is to assign a string price to the document.cookie object, that feels like this:

What is JQuery ?

JQuery may be a client-side JavaScript library that abstracts away browsers’ totally different implementations into associate easy-to-use API. What jQuery will best is to move with the DOM (add, modify, take away components on your page), do Ajax requests, produce effects (animations) and then forth. It doesn't give associate application framework, it’s just a tool amongst others that ought to be used what it’s meant to be used for. However, there’s a superfluity of plugins owing to a thriving community, and there’s just about a plugin for all the world you'll be able to consider.

Recently, it additionally set a replacement usage record with being employed on fifty four per cent of Alexa’s high seventeen,000 most visited websites, whereas Flash was “only” at forty seven per cent.

Before we tend to continue, I’d prefer to quote @johanbrook UN agency, once I asked what I ought to mention to those who won't have used jQuery before, said: Don’t head to bed with it. That said, jQuery continues to be the most effective library for DOM manipulation, Ajax and effects and during this article you’ll determine why.

How do i exploit jQuery?

First off, you must learn some basics. jQuery, like several different libraries, uses the world $ variable as a cutoff. Basically, window.jQuery === window.$ (and thus, $("div") and jQuery("div") ar identical. you'll be able to use whichever you favor, however $ is shorter and neater, it additionally provides higher readability since it’s easier to identify than jQuery, that may be a a lot of standard name for a variable (being plain text). There ar 2 elements to jQuery. There ar ways that run on collections and place confidence in $.fn (a cutoff for $.prototype). There ar then utility ways that run directly on $—for example $.data() and $.ajax(), that don’t need a group to figure.

Using selectors and instance ways

jQuery sports a CSS3 selector engine known as Sizzle, which implies that a lot of or less all selectors you utilize in your stylesheet may be applied to the DOM to question for components matching them. think about the subsequent markup:

What is Json ?

JSON stands for JavaScript Object Notation, that may be a thanks to format information in order that it is transmitted from one place to a different, most ordinarily between a server and an internet application. The JSON format was specific by politician Crockford.

JSON relies on the JavaScript programing language, however is utilized in most different languages by employing a special JSON program. this permits information to be transmitted from a server to each server-side and client-side applications, permitting JSON to be used as an alternate to XML for gathering information. Below is associate example of JSON data:

Basically, JSON formats information into JavaScript objects and permits for name and worth pairs, arrays, strings, and different information varieties. once this information is scan by a JSON program, it's regenerate into the acceptable information kind within the programing language being employed. this permits for fast retrieval of the info in a very format that's already usable. once saving JSON information, the file extension used is .json.






What is HTML ?

HTML, that stands for machine-readable text nomenclature, could be a nomenclature wont to produce websites. the net developer uses "HTML tags" to format completely different components of the document. for instance, you utilize markup language tags to specify headings, paragraphs, lists, tables, pictures and far additional.

HTML could be a set of ordinary Generalized nomenclature (SGML) and is nominal by the globe Wide internet pool (W3C).

What do i want to form HTML?
You don't want any special instrumentality or software package to form markup language. In fact, you almost certainly have already got everything you wish. Here is what you need:

Computer
Text or markup language editor. Most computers have already got a text editor and you'll be able to simply produce markup language files employing a text editor. Having aforementioned that, there area unit definite advantages to be gained in downloading associate markup language editor. though text editors area unit associate possibility, i do not understand any serious internet developer WHO really uses one to code their websites!
CoffeeCup is one in all the foremost fashionable markup language editors on the net.

If you do not have the money to buy associate editor, you'll be able to forever transfer a free one. Examples embrace SeaMonkey, CoffeeCup free version (Windows) and TextPad (Windows).

If you do not have associate markup language editor, and you do not need to transfer one just, a text editor is okay. Most computers have already got a text editor. samples of text editors embrace pad of paper (for Windows), Pico (for Linux), or Simpletext/Text Edit/Text Wrangler (Mac).

Web Browser. for instance, net person, Firefox, or Google Chrome.
Do i want to be online?
No, you are doing not ought to be on-line to form websites. you'll be able to produce websites on your native machine. you merely ought to log on once you need to publish your website to the net - this bit comes later.

The next lesson can show you ways to form an online page in but five minutes.

Profileer Vs SPFile in Oracle

 When associate degree Oracle Instance is started, the characteristics of the Instance ar established by parameters such at intervals the data format parameter file. These data format parameters ar either hold on in an exceedingly PFILE or SPFILE. SPFILEs ar obtainable in Oracle 9i and higher than. All previous releases of Oracle ar victimisation PFILEs.

SPFILEs offer the subsequent benefits over PFILEs:

An SPFILE is backed-up with RMAN (RMAN cannot backup PFILEs)
Reduce human errors. The SPFILE is maintained by the server. Parameters ar checked before changes ar accepted.
Eliminate configuration issues (no have to be compelled to have a neighborhood PFILE if you wish to begin Oracle from a foreign machine)
Easy to seek out - hold on in an exceedingly central location
What is the distinction between a PFILE and SPFILE:

A PFILE may be a static, client-side document that has got to be updated with a regular text editor like \"notepad\" or \"vi\". This file usually reside on the server, however, you wish a neighborhood copy if you wish to begin Oracle from a foreign machine. DBA\'s normally ask this file because the INIT.ORA file.

An SPFILE (Server Parameter File), on the opposite hand, may be a persistent server-side computer file that may solely be changed with the \"ALTER SYSTEM SET\" command. this suggests you not want a neighborhood copy of the pfile to begin the info from a foreign machine. piece of writing associate degree SPFILE can corrupt it, and you\'ll not be able to begin your info any longer.

How can i do know if my info is employing a PFILE or SPFILE:

Execute the subsequent question to envision if your info was started with a PFILE or SPFILE:

SQL> choose DECODE(value, NULL, \'PFILE\', \'SPFILE\') \"Init File Type\" 
       FROM sys.v_$parameter wherever name = \'spfile\';
You can additionally use the V$SPPARAMETER read to ascertain if you\'re employing a PFILE or not: if the \"value\" column is NULL for all parameters, you\'re employing a PFILE.

Viewing Parameters Settings:

One will read parameter values victimisation one in every of the subsequent strategies (regardless if they were set via PFILE or SPFILE):

The \"SHOW PARAMETERS\" command from SQL*Plus (i.e.: SHOW PARAMETERS timed_statistics)
V$PARAMETER read - show the presently in impact parameter values
V$PARAMETER2 read - show the presently in impact parameter values, however \"List Values\" ar shown in multiple rows
V$SPPARAMETER read - show the present contents of the server parameter file.
Starting a info with a PFILE or SPFILE:

Oracle searches for an appropriate data format parameter go in the subsequent order:

Try to use the spfile$.ora go in $ORACLE_HOME/dbs (Unix) or ORACLE_HOME/database (Windows)
Try to use the spfile.ora go in $ORACLE_HOME/dbs (Unix) or ORACLE_HOME/database (Windows)
Try to use the init$.ora go in $ORACLE_HOME/dbs (Unix) or ORACLE_HOME/database (Windows)
One will override the default location by specifying the PFILE parameter at info startup:

SQL> STARTUP PFILE=\'/oradata/spfileORCL.ora\'

Note that there\'s not constant \"STARTUP SPFILE=\" command. One will solely use the higher than choice with SPFILE\'s if the PFILE you purpose to (in the instance above), contains one \'SPFILE=\' parameter inform to the SPFILE that ought to be used. Example:

SPFILE=/path/to/spfile

Changing SPFILE parameter values:

While a PFILE is altered with any text editor, the SPFILE may be a computer file. The \"ALTER SYSTEM SET\" associate degreed \"ALTER SYSTEM RESET\" commands is accustomed amendment parameter values in an SPFILE. look into these examples:

SQL> ALTER SYSTEM SET open_cursors=300 SCOPE=SPFILE;

SQL> ALTER SYSTEM SET timed_statistics=TRUE
COMMENT=\'Changed by Frank on one Gregorian calendar month 2003\'
SCOPE=BOTH
  SID=\'*\';
The SCOPE parameter is set to SPFILE, MEMORY or BOTH:

- MEMORY: Set for the present instance solely. this is often the default behaviour if a PFILE was used at STARTUP.

- SPFILE: update the SPFILE, the parameter can go with next info startup

- BOTH: have an effect on the present instance and persist to the SPFILE. this is often the default behaviour if associate degree SPFILE was used at STARTUP.
The COMMENT parameter (optional) specifies a user remark.

The SID parameter (optional; solely used with RAC) indicates the instance that the parameter applies (Default is *: all Instances).

Use the subsequent syntax to line parameters that take multiple (a list of) values:

SQL> ALTER SYSTEM SET utl_file_dir=\'/tmp/\',\'/oradata\',\'/home/\' SCOPE=SPFILE;

Use this syntax to line unsupported data format parameters (obviously only if Oracle Support instructs you to line it):

SQL> ALTER SYSTEM SET \"_allow_read_only_corruption\"=TRUE SCOPE=SPFILE;

Execute one in every of the subsequent command to get rid of a parameter from the SPFILE:

SQL> ALTER SYSTEM RESET timed_statistics SCOPE=SPFILE SID=‘*’;
SQL> ALTER SYSTEM SET timed_statistics = \'\' SCOPE=SPFILE;
Converting between PFILES and SPFILES:

One will simply migrate from a PFILE to SPFILE or the other way around. Execute the subsequent commands from a user with SYSDBA or SYSOPER privileges:

SQL> produce PFILE FROM SPFILE; 
SQL> produce SPFILE FROM PFILE;
One can even specify a non-default location for either (or both) the PFILE and SPFILE parameters. look into this example:

SQL> produce SPFILE=\'/oradata/spfileORCL.ora\' from PFILE=\'/oradata/initORCL.ora\';

Here is another procedure for ever-changing SPFILE parameter values victimisation the higher than method:

Export the SPFILE with: produce PFILE=‘pfilename’ FROM SPFILE = ‘spfilename’;
Edit the ensuing PFILE with a text editor
Shutdown and startup the info with the PFILE option: STARTUP PFILE=filename
Recreate the SPFILE with: produce SPFILE=‘spfilename’ FROM PFILE=‘pfilename’;
On succeeding startup, use STARTUP while not the PFILE parameter and therefore the new SPFILE are going to be used.
Parameter File Backups:

RMAN (Oracle\'s Recovery Manager) can backup the SPFILE with the info management file if setting \"CONFIGURE CONTROLFILE AUTOBACKUP\" is ON (the default is OFF). PFILEs can\'t be backed-up with RMAN. look into this example:

RMAN> put together CONTROLFILE AUTOBACKUP ON;

Use the subsequent RMAN command to revive associate degree SPFILE:

RMAN> RESTORE CONTROLFILE FROM AUTOBACKUP;

JavaScript Switch Statement

In the previous lesson regarding JavaScript If statements, we have a tendency to learned that we will use AN If Else If statement to check for multiple conditions, then output a special result for every condition.

For example, if the variable myColor was up to Blue, we have a tendency to might output one message. If it's Red we have a tendency to might output another, etc

Another way of doing this can be to use the JavaScript Switch statement. a plus of exploitation the switch statement is that it uses less code, that is best if you have got plenty of conditions that you just got to check for.

Exlanation of code:
When the user clicks any of the radio buttons, the onclick event handler calls the analyzeColor() perform. after we decision that perform, we have a tendency to pass within the worth of the radio button (using this.value). The perform then takes that worth and performs a switch statement on that.
The switch statement's initial line is switch (myColor). this implies that it'll perform its tests against the worth of the myColor variable.
This line is followed by a collection of "cases" inside crisp braces. it is vital to use "break" when every case - this prevents the code from running into successive case. within the case of the colour being Blue, it displays AN alert box with a message bespoken thereto color. a similar for Red. The default condition is just dead if the opposite 2 are not true (i.e. the chosen color is neither Blue nor Red).

JavaScript Try-Catch

The a lot of JavaScript you code the a lot of errors you will encounter. this is often a reality of life in any programming atmosphere. Nobody's good and, once your scripts become a lot of complicated, you will find there square measure generally eventualities that end in a slip that you just did not think about.

JavaScript errors on web content will scare your guests away. what number times have you ever encountered an online page with errors, solely to click the "back" button?

OK, therefore you cannot continually forestall errors from occuring, however you'll do one thing concerning them. The JavaScript "Try... Catch" statement helps you handle errors in an exceedingly "nice" approach.

To use the attempt... Catch statement, you are taking any code you're thinking that may doubtless end in a slip, and wrap it inside the "try" statement. You then code what you wish to happen within the event of a slip and wrap that in an exceedingly "catch" statement.

The on top of code can hide the error and gift one thing a lot of user friendly to the user. this is often as a result of the code with the error was wrapped within a "try" statement. And, as a result of there was a slip, the browser outputs no matter is between the "catch" statement.

JavaScript While Loop

In JavaScript and most different languages, "loops" modify your program to unendingly execute a block of code for a given range of times, or whereas a given condition is true.

The JavaScript whereas loop executes code whereas a condition is true.

For example, you may create your program show a the worth of a counter whereas the count is a smaller amount than or adequate to say, 10.


Exlanation of code:

We started by declaring a variable referred to as "myBankBalance" and setting it to zero
We then opened a minute loop, inserting our condition between brackets. Our condition checks if this price of the myBankBalance variable is a smaller amount than or adequate to ten.
This is followed by code to execute whereas the condition is true. during this case, we tend to area unit merely, outputting this price of myBankBalance, preceded by some text. This code is placed among wavy braces.
We then increment the worth by one.
When the browser reaches the closing wavy brace, if the condition continues to be true, it goes back to the primary wavy brace and executes the code once more. Of course, by now, the myBankBalance variable has been incremented by one. If the condition isn't true (i.e. the variable is larger than 10), it exits from the loop.

JavaScript Events

In the previous lesson, we tend to used an incident handler (also called AN intrinsic event) to activate a decision to our perform. There area unit many various event handlers that you simply will use to link your hypertext mark-up language components to a bit of JavaScript.

When you write a JavaScript perform, you'll got to verify once it'll run. Often, this can be once a user will one thing like click or hover over one thing, submit a type, double clicks on one thing etc.

These area unit samples of events.

Using JavaScript, you'll be able to answer an incident exploitation event handlers. you'll be able to attach an incident handler to the hypertext mark-up language part that you would like to retort to once a selected event happens.

For example, you'll attach JavaScript's onMouseover event handler to a button and specify some JavaScript to run whenever this event happens against that button.

HTML five Event Handlers
HTML version five introduced more event handlers. I've intercalary them to HTML5 Event Handlers, thus make sure to visualize them out.

The events listed here offer you with several opportunities to trigger some JavaScript from at intervals your hypertext mark-up language code.

I encourage you to marker this page as a reference - soon you will would like a reminder of that events you'll be able to use once determination a specific secret writing issue.

JavaScript Functions

In JavaScript, you may use functions lots. A operate (also called a method) may be a self-contained piece of code that performs a specific "function". you'll recognise a operate by its format - it is a piece of descriptive text, followed by open and shut brackets.

Sometimes there'll be text in between the brackets. This text is understood as AN argument. AN argument is passed to the operate to supply it with more information that it has to method. This information may well be totally different counting on the context within which the operate is being referred to as.

Arguments may be extraordinarily handy, like permitting your users to supply data (say via a form) that's passed to a operate to method. for instance, your users may enter their name into a kind, and therefore the operate would take that name, do some process, then gift them with a personalized message that has their name.

A operate does not truly do something till it's referred to as. Once it's referred to as, it takes any arguments, then performs it's operate (whatever that will be).

Exlanation of code

Writing the function:

We started by victimisation the operate keyword. This tells the browser that a operate is on the brink of be outlined
Then we tend to gave the operate a reputation, therefore we tend to created up our own name referred to as "displayMessage". we tend to such as the name of AN argument ("firstName") that may be passed in to the present operate.
After the operate name came a curly  bracket {. This opens the operate. there's additionally a closing bracket later, to shut the operate.
In between the curly  brackets we tend to write all our code for the operate. during this case, we tend to use JavaScript's inbuilt alert() operate to pop a message for the user.


Calling the function:

We created AN hypertext mark-up language kind with AN input field and submit button
We allotted a reputation ("yourName") to the input field
We more the onclick event handler to the button. This event handler is termed once the user clicks on the button (more concerning event handlers later). this can be wherever we tend to decision our JavaScript operate from. we tend to pass it the worth from the form's input field. we are able to reference this worth by victimisation "form.yourName.value".

Friday, 18 October 2013

How to create arrays in JavaScript ?

We can declare an array like this
var scripts = new Array(); 

We can add elements to this array like this

scripts[0] = "ASP";
scripts[1] = "ADO";
scripts[2] = "CSharp";
scripts[3] = "HTML";

Now our array scripts has four elements inside it and we can access them by using their index number, which  will be starts from 0. To get the third element of the array we have to use the index number

2 . Here is the way to get the third element of an array.
document.write(scripts[2]);
We also can create an array like this
var no_array = new Array(21, 22, 23, 24, 25);

How to different JavaScript from Java ?

JavaScript was developed by Brendan Eich of Netscape; Java was developed at Sun Microsystems. whereas the 2 languages share some common syntax, they were developed severally of every alternative and for various audiences. Java may be a full-fledged artificial language tailored for network computing; it includes many its own objects, together with objects for making user interfaces that seem in Java applets (in internet browsers) or standalone Java applications. In distinction, JavaScript depends on no matter surroundings it's operational sure the computer program, like an internet document's kind parts. 

JavaScript was at first referred to as LiveScript at browser whereas it absolutely was below development. A licensing deal between browser and Sun at the minute let browser plug the "Java" name into the name of its scripting language. Programmers use entirely totally different tools for Java and JavaScript. it's additionally not uncommon for a applied scientist of 1 language to be blind to the opposite. the 2 languages do not place confidence in one another and ar supposed for various functions. In some ways that, the "Java" name on JavaScript has confused the world's understanding of the variations between the 2. On the opposite hand, JavaScript is far easier to find out than Java and may supply a mild introduction for newcomers WHO wish to graduate to Java and also the styles of applications you'll be able to develop with it.

JavaScript Coding Guidelines

Documentation comments for files should looks like:
/**
 * @description       Description of the file.
 * @subdescription Some subdescription what the file contains.
 * @package           Name of the mainpackage.
 * @version            Version of the packages/subpackages.
 * @subpackage     Name of the subpackages.
 * @author             Name of the Author <mail>.
 * @copyright         Year, Name of the copyright holder.
 * @license             Name of the License.
 */

Documentation comments for functions should looks like:
/*!
 * @functionname functionname
 * @description     The description what the function does.
 * @param1 type  The parameter of the function.
 * @return type    What will be returned.
 */

Reason: If you have a structure like you see above, a parser can create documenations.
The parser will readout these placeholders and create an HTML-document.


Use the "use strict” string, to keep your code right and clean.
If a browser breaks because of some part of the code, then you should write it better.
Reason: http://javascriptweblog.wordpress.com/2011/05/03/javascript-strict-mode/ (Clean code reason.)


Avoid global variables.
Reason: http://sharjes.de/javascript-performance-globale-variablen-vermeiden/ (Performance reason.)


Use correct variable/function/object identifier.
Your names should looks like the examples below. Understandable names, camelCaseNames, not to short, not to long.
Reason: A well named variable/function/object is more readable because you have a clue as to what it means. (Clean code reason)

wrong:
var a = 2;
var f = function() …
var o = {
};
var ThisIsMyCounterVariable = 2;

right:
var counterVar = 2;
var toBool = function() …
var personObj = {
};


Use shortend assigments.
Reason: http://sharjes.de/javascript-performance-objekte/ (Performance reason.)

wrong:
var obj = new Object();
var arr = new Array();

Right:
var obj = {};
var arr = [];


One-Line-Comments should looks like:
// After the slashes is a space, line begins with a capital letter and ends with a period.


Multi-Line-Comments should looks like:
/*
 * All asterisk-symbols form a new line.
 * After the asterisk-symbol should be a space.
 * Lines begin with a capital letter and ends with a period.
 * If the line is too long, then it ends with a plus+
 * and the letter on the next line starts with a lower case letter.
 */

Reason: Clearer and more readable. Some parsers show it as a tip.
Tip: You can write /** / SourceCode /**/ (Single-line- and Multi-line-comment support) to quickly comment/uncomment code. A space between * and / will comment out your code. You can quickly comment/uncomment it when you make a space or delete the space.


Always use the “var” keyword!
Makes a clean code and avoids false results.
Reason: http://bustingseams.blogspot.com/2009/08/another-javascript-pitfall-hoisting.html http://net.tutsplus.com/tutorials/javascript-ajax/quick-tip-javascript-hoisting-explained/
(Scope, hoisting, performance and clean code reason)

Wrong:
function foo()
{

}
myVar = 2;

Right:
var foo = function()
{

};
var myVar = 2;


Avoid spaces as you can see below.
Reason: More readable.

Wrong:
function ( arg1, arg2, … )
for ( var i = 0; ... )
for ( var item in collection )
if ( !foo )

Right:
function(arg1, arg2, …)
for(var i = 0; ...)
for(var item in collection)
if(!foo)


Set open brackets in a new line, except with javascript objects.
Reason: Better readable.

Wrong:
var foo = function(){
};

if(true){

}

var obj =
{
   foo: ""
};

// Doesnt work correctly, because return is the end and no code after return will be executed.
return
{
   init: init
}

Right:
var foo = function()
{

};

if(true)
{

}

var obj = {
   foo: ""
}

return {
   init: init
}


Use always 3 spaces.
Reason: More readable.

Wrong:
var foo = function()
{
alert(123);
};

if(true)
{
alert(123);
}

Right:
var foo = function()
{
   alert(123);
};

if(true)
{
   alert(123);
}


Use shortend ifs as you can:
Reason: More readable.

return (foo === null) ? "foo is null" : foo; // Only an example.


Use identity/not identity operator (=== / !==)
instead of equal/not equal operator (== / !=)

Reason: http://longgoldenears.blogspot.com/2007/09/triple-equals-in-javascript.html (Performance reason.)
If you check a boolean variable for true or false, use the shortend version:
Reason: More readable.

Wrong:
if( myVar == true) …
if(myVar === true) …
if(myVar != true) …

Right:
if(myVar) // True.
if(!myVar) // False.

Always use semicolons after closing brackets of a function!
One more is better than forget some, a minifier will delete this!

Wednesday, 16 October 2013

JavaScript Variables

Variables in JavaScript behave identical as variables in most well liked programming languages (C, C++, etc) do, however in JavaScript you do not ought to declare variables before you employ them. If you do not understand what declaring is, don't be concerned concerning it. it is not important!

Javascript exploitation variables:
A variable's purpose is to store data in order that it may be used later. A variable could be a symbolic name that represents some knowledge that you just set. To think about a variable name in world terms, image that the name could be a poke and therefore the knowledge it represents ar the groceries. The name wraps up the info therefore you'll move it around lots easier, however the name isn't the data!

Variable example:
When employing a variable for the primary time it's not necessary to use "var" before the variable name, however it's a decent programming apply to form it crystal clear once a variable is being employed for the primary time within the program. Here we tend to ar showing however identical variable will withstand totally different values throughout a script.

Example:
<body>
<script type="text/JavaScript">
<!--
var linebreak = "<br />"
var my_var = "Hello World!"

document.write(my_var)
document.write(linebreak)

my_var = "I am learning JavaScript!"
document.write(my_var)
document.write(linebreak)

my_var = "Your Content Here."
document.write(my_var)
//-->
</script>
</body>


OutPut:
Hello World!
Yor Content Here


We created 2 variables during this example--one to carry the HTML for a line break and therefore the alternative for a dynamic variable that had a complete of 3 totally different values throughout the script.

To assign a worth to a variable, you employ the equal sign (=) with the variable on the left and therefore the price to be appointed on the correct. If you swap the order, your script won't work correctly! In English, the JavaScript "myVar = 'Hello World!'" would be: myVar equals 'Hello World!'.

The first time we tend to used a variable, we tend to placed volt-ampere before to suggest its 1st use. this is often a straightforward thanks to organize the variables in your code and see once they came into existence. In sequent assignments of identical variable, we tend to didn't want the volt-ampere.

Javascript variable naming conventions:
When selecting a variable name, you want to 1st make sure that you just don't use any of the JavaScript reserved names Found Here. Another smart apply is selecting variable names that ar descriptive of what the variable holds. If you've got a variable that holds the scale of a shoe, then name it "shoe_size" to form your JavaScript additional clear.

A good rule of thumb is to possess your variable names begin with a small letter (a-z) and use underscores to separate a reputation with multiple words (i.e. my_var, strong_man, happy_coder, etc).

Tuesday, 15 October 2013

Javascript Operators

Operators in JavaScript ar terribly almost like operators that seem in alternative programming languages. The definition of associate operator may be a image that's wont to perform associate operation. most frequently these operations ar arithmetic (addition, subtraction, etc), however not forever.

Airthmetic Operator List:

OperatorEnglishExample
+Addition2 + 4
-Subtraction6 - 2
*Multiplication5 * 3
/Division15 / 3
%Modulus43 % 10

Modulus % could also be a replacement operation to you, however it's simply a special method of claiming "finding the remainder". after you perform a division like 15/3 you get five, exactly. However, if you are doing 43/10 you get a solution with a decimal, 4.3. ten goes into forty fourfold so there's a leftover. This leftover is what's came by the modulus operator. forty three the ten would equal three.


Javascript operator example with variables:
Performing operations on variables that contain values is extremely common and straightforward to try to to. Below may be a easy script that performs all the essential arithmetic operations.

Example Code:
<body>
<script type="text/JavaScript">
<!--
var two = 2
var ten = 10
var linebreak = "<br />"

document.write("two plus ten = ")
var result = two + ten
document.write(result)
document.write(linebreak)


document.write("ten * ten = ")
result = ten * ten
document.write(result)
document.write(linebreak)

document.write("ten / two = ")
result = ten / two
document.write(result)
//-->
</script>
</body>


Output:
two plus ten = 12
ten * ten = 100
ten / two = 5


Comparison Operators in JavaSciript:
Comparisons ar wont to check the connection between variables and/or values. one equal sign sets a worth whereas a double equal sign (==) compares 2 values. Comparison operators ar used within conditional statements and value to either true or false. we are going to speak additional regarding conditional statements within the forthcoming lessons.

OperatorEnglishExampleResult
==Equal Tox == yfalse
!=Not Equal Tox != ytrue
<Less Thanx < ytrue
>Greater Thanx > yfalse
<=Less Than or Equal Tox <= ytrue
>=Greater Than or Equal Tox >= yfalse

C

External Javascript

Having already mentioned putting JavaScript within the head and body of your markup language document, allow us to currently explore the third attainable location kind -- associate degree external file. If you've got ever used external CSS before, this lesson are going to be a cinch.

Importing associate degree external javascript file:
Importing associate degree external file is comparatively painless. First, the file you're commercialism should be valid JavaScript, and solely JavaScript. Second, the file should have the file extension ".js". Lastly, you want to recognize the placement of the file.

Let us assume we've got a file "javascriptoverview.js" that contains a 1 line greeting World alert perform. Also, allow us to assume that the file is that the same directory because the markup language file we tend to ar about to code up. To import the file you'd do the subsequent in your markup language document.

Great javascript repositories
There is a large amount of nice stuff you'll be able to do with JavaScript, if you recognize the way to code like Paul Allen and William Henry Gates, except for the remainder people, it's nice to urge unbelievable JavaScript tools while not having to put in writing them ourselves. Below ar a number of the higher JavaScript resources on the net recently.

  • JavaFile.com
  • Java-Scripts.com
  • Drop Down JavaScript Menus

External file tips and recap:
  • Use external JavaScript files once you need to use identical script on several pages, however don't desire to own to rewrite the code on each page!
  • Use external JavaScript files for as well as each sorts of scripts: {the kind|the sort|the kind} that you simply place in the top (functions) and therefore the type you place within the body (scripts you would like to run once the page loads).
  • Be sure that your JavaScript files (.js) don't embody the

where we Can write JavaScript Code

There square measure 3 general areas that JavaScript are often placed to be used during a webpage.


  • Inside the pinnacle tag
  • Within the body tag (like our example within the previous lesson)
  • In associate external file (we'll cite this next lesson)


The location alternative of head or body is extremely straightforward. If you wish to possess a script run on some event, like once a user clicks somewhere, then you'll place that script within the head. If you wish the script to run once the page hundreds, like our "Hello World!" example within the previous lesson, then you'll wish to position the script among the body tag.

External JavaScript files and their uses are going to be mentioned within the next lesson.

Example head script:
Since we've already seen the type of script that goes within the body, however concerning we have a tendency to write a script that takes place once some event occurs? Let's have associate alert show up once a user click on a button.

HTML and JavaScript Code:
<html>
<head>
<script type="text/JavaScript">

function popup() {
alert("Hello My JavaScript Tutorials")
}

</script>
</head>
<body>
<input type="button" onclick="popup()" value="popup">
</body>
</html>

We created a perform referred to as popup and placed it within the head of the hypertext markup language document. currently whenever somebody clicks on the button (this is associate event), associate alert can pop with "Hello World!". we'll get in additional depth on functions and events during a later lesson.



JavaScript is enabled or not ?

This lesson can initial teach you the way to alter JavaScript in net mortal, Firefox, and Opera, then show you the way you'll be able to write a awfully easy script to separate web site guests WHO do not have JavaScript enabled from people who do.

Enable JavaScript in Explorer
In net mortal 6/7 (download net Explorer), you'll be able to check to examine if JavaScript is enabled by navigating to the custom security settings that ar somewhat buried (don't worry; we'll assist you notice it).


  • Click on the Tools menu
  • Choose net choices... from the menu
  • Click the protection tab on the net choices pop
  • Click the Custom Level... button to access your security settings
  • Scroll most the approach all the way down to the Scripting section
  • Select the alter button for Active scripting
  • Click alright to end the method
  • Click affirmative once asked to verify


Enable JavaScript in Firefox:
In Firefox two (download Firefox) you'll be able to check to examine if JavaScript is enabled by navigating to the Content settings beneath choices.


  • Click on the Tools menu
  • Choose choices... from the menu
  • Click the Content tab within the choices pop
  • Make sure that alter JavaScript is checked
  • Click alright to end the method


Enable Javascript in Opera

In Opera (download Opera) you'll be able to check to examine if JavaScript is enabled by navigating to the Content settings beneath Preferences.


  • Click on the Tools menu
  • Choose Preferences... from the menu
  • Click the Advanced tab within the Preferences pop
  • Select Content from the list of things on the left
  • Make sure that alter JavaScript is checked
  • Click alright to end the method

JavaScript Detection:
These days, it's essentially not possible to navigate the online while not a JavaScript-enabled browser, therefore checking whether or not or not a user has JavaScript enabled isn't all that necessary. likelihood is that, the sole approach it's disabled is that if the company's IT employees has set to disable JavaScript for a few reason. However, if you continue to wish to make sure your users ar JavaScript enabled, this script can savvy done.

The solely certain fireplace thanks to separate users WHO do not have JavaScript from people who do is to use an easy send script that may only work for those with JavaScript enabled. If a human browser doesn't have JavaScript enabled, the script won't run, and that they can stay on an equivalent page.


JavaScript Code Sysntax

If you have got ever used CSS before, you'll notice the total half regarding as well as JavaScript are lots easier to understand. Here necessary steps you ought to perpetually follow once making or mistreatment somebody else's JavaScript code:


  • Use the script tag to inform the browser you're mistreatment JavaScript.
  • Write or transfer some JavaScript
  • Test the script!

There are such a lot of various things that may get it wrong with a script, be it human error, browser compatibility problems, or software package variations. So, once mistreatment JavaScript, take care that you simply take a look at your script out on a large sort of systems and most significantly, on completely different internet browsers.

Your Initial Javascript:
To follow the classic samples of several programming tutorials, let's use JavaScript to print out "Hello World" to the browser. i do know this is not terribly attention-grabbing, however it'll be a decent thanks to make a case for all the overhead needed to try and do one thing in JavaScript.

<html>
<body>
<script type="text/JavaScript">

document.write("Hello World!")

</script>
</body>
</html>

Output:
Hello World! 


Javascript Overview

Javascript-- what the euphemism is it? Is it a very tough artificial language that casual internet designers ought to be afraid of ? what's it used for? Hopefully we'll be able to answer these queries for you and a lot of during this tutorial

JavaScript has been around for many years currently, in many alternative flavors. the most advantage of Javascript is to feature further interaction between the web site and its guests with simply alittle further work by the online developer. Javascript permits industrious internet masters to induce a lot of out of their web site than markup language and CSS will give.

By definition, JavaScript could be a client-side scripting language. this suggests the online surfer's browser are going to be running the script. the alternative of client-side is server-side, that happens during a language like PHP. PHP scripts area unit travel by the online hosting server.

There area unit several uses (and abuses!) for the powerful JavaScript language. Here area unit some things that you just might or might not have seen in your internet surfriding days:


  • Clocks
  • Mouse Trailers (an animation that follows your mouse after you surf a site)
  • Drop Down Menus
  • Alert Messages
  • Popup Windows
  • HTML type knowledge Validation


Tutorial Summary:
Before you start this tutorial, you must have basic information of markup language. abreast of|cross-check|look at|verify|scrutinize} our Beginner and markup language tutorials to brush up on the fundamentals.

This tutorial can cowl the fundamentals of JavaScript, from wherever to put your JavaScript all the thanks to creating your own JavaScript functions. Also, there'll be some sensible programming follow tips throughout this tutorial.

We suggest that you just scan some lessons each day and follow what you have got learned. this can assist you to soak up the fabric a lot of promptly than if you blasted through the complete tutorial in one sitting!