Get url parameters and their values using javascript

In this programming tutorial, we will learn how to get url parameters and their values using javascript. Recently, while working on a project, i needed to get parameter values from url string of the current web page. So let's have a look over how i made this happen.

Get url parameters and their values using javascript

// Read the page's GET url variables and return them as an associative array.
function getUrlParametersVals()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}
Now let's have a look over how to call this getUrlParametersVals() function.

This function returns an associative array with url parameters and their values. For example, let's suppose we have the following URL

http://www.yourwebsitecom/contact.php?name=Adeel&country=Pakistan 

Calling getUrlParametersVals() function would return you the following array:
{
    "name"    : "Adeel",
    "country" : "Pakistan"
}
To get the value of first parameter you will do this
var myName = getUrlParametersVals()["name"];
To get the value of second parameter you will do the same
var myCountry = getUrlParametersVals()["country"];
So that's it. 


I hope you will find this tutorial very informative. 

I love your feedback.
Read more...

New iPad joystick promises more accurate gaming actions

Now iPad and other tablets have got their own joystick. Logitech has leapt into the gadget-accessory fray with a tool it claims will help you to remove a poorly aimed rocket blast.

The Logitech Joystick is clearly focus to make the gaming experience on the iPad closer to what gamers enjoy on more dedicated gaming devices.

"No one likes to lose a point or go down to defeat because their thumb misses the control area," the company says on its Website for the $19.99 gadget.."The Logitech Joystick provides you a thumb-stick style game controller for iPad that you can use with just about any game with an on-screen joystick or d-pad."

This joystick attaches to the iPad screen with suction cups, allowing the user move it around depending on the game. A coiled spring keeps the stick centered.

The site lists 32 games that the joystick is currently compatible with. That list is heavily weighted toward sports games and shooters that made a splash on traditional gaming consoles before being reworked for the iPad.

Among them: "Madden NFL 11," "Call of Duty World at War: Zombies," "FIFA '11," "Prince of Persia: Warrior Within" and "Resident Evil 4."

More casual titles like "Cut the Rope" and "Fruit Ninjas" are nowhere to be seen, a likely nod to the fact that many of those games require swiping at multiple spots instead of being focused largely in one place.

The Wall Street Journal notes that the product is part of an increased focus on tablet accessories by Logitech, which has struggled somewhat as Apple's ascendance has hurt its PC-accessory trade.

CNET noted that the joystick, which is available for pre-order and set to ship in September, looks similar to the already available Fling Joystick, which performs a similar function and is offered at the same price. Source by CNN
Read more...

Get last character of a string in javascript

In this programming tutorials you will learn how to get last character of a string in javascript. Javascript is a very powerful client side language and there are various methods in it to get last character of a string. So let's have a look over the code snippet given below.
Get last character of a string in javascript
Method 1
Method 2 So that's it. I hope you will find this tutorial very handy. Happy Coding, Keep Coding. I love your feedback.
Read more...

Remove first character of a string in javascript

In this programming tutorial we will learn how to remove first character of a string in javascript. I have already written a tutorial that demonstrates how to remove last character of a string in javascript. Removing first character of a string can be easily done by using some built-in javascript functions. I will discuss two methods to achieve the task. Let's have a look over the examples given below.
Remove first character of a string in javascript
Method 1
var myString="Hello World!";
// newString will contain 'ello World!'
var newString=myString.substring(1);
Method 2
var myString="Hello World!";
// newString will contain 'ello World!'
var newString=myString.slice(1,myString.length);
So that's it. I hope you will find this tutorial very handy.
I love your feedback.
Read more...

Remove last character of a string in javascript

In this programming tutorial we will learn how to remove last character of a string in javascript. It can be easily done by using some built-in javascript functions. I will discuss two methods to achieve the goal. Let's have a look over the code snippet given below.
Remove last character of a string in javascript
Method 1
var myString="Hello World!";
// newString will contain Hello World!
var newString = myString.substring(0, myString.length-1);
In the above method, we have a string 'hello world!', the newString subtract the string, take the character range from the first to the second last character of a string, and we will get the new string newString 'hello world'.
Method 2
var myString="Hello World!";
var newString = myString.slice(0, -1);// newString contains Hello World!
In the above method we are using the javascript built-in function slice(). Using slice() we can extract any part of the string . This function needs two parameters p1 and p2. Value of p1 indicates the starting position of the sub string and value of p2 gives the length of the sub string. The first position (left side) of the main string is known as 0 position of the string. Say for example we want sub string of length 5 characters from left side of the main string so here we have to use slice(0,5) . In our example we don't want to get the last character of a string that's why we use slice(0,-1). If we want to remove last two characters then definitely we will use slice(0,-2).

So that's it. This is the way to remove last character of a string in javascript.
I love your feedback.
Read more...

Remove spaces in a string using jquery

In this programming tutorial you will learn how to remove spaces in a string using jquery. Its quite easy in jquery. I will us the built-in replace() method to do it. Let's have a look over the following code snippet.

Remove spaces in a string using jquery
<html xmlns="http://www.w3.org/1999/xhtml">

<head>

    <title>Remove all spaces in a string using jquery</title>

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script></script>

    <script type="text/javascript">

        $(function () {

            var spanText = $("#spanOne").html();

            $("#spanTwo").html(spanText.replace(/\s/g, ""));

        });

    </script>

</head>

<body>
   <p><strong>Before</strong></p>

   <p><span id="spanOne">For more bundle of jquery tutorials, stay tuned with nice-tutorials.blogspot.com</span></p>

    <p><strong>After</strong></p>

    <p><span id="spanTwo"></span></p>

</body>

</html>

Output
Remove spaces in a string using jquery
So that's it. Using regular expression within replace method we have successfully remove spaces in a string using jquery.



I love your feedback.
Read more...

Get day of a given date in javascript

In this programming tutorial we will learn how to get day of a given date in javascript. It is quite easy in javascript with the help of its built-in Date() object. Let's have a look over the following code sinppet.
Get day of a given date in javascript


The getDay() method returns the day of the week (from 0 to 6) for the specified date, according to your local time.

Note: Sunday is 0, Monday is 1, and so on. This method is always used in conjunction with a Date object.

So that's it. This is the way to get day of a given date in javascript.
I love your feedback.
Read more...

create div element in jquery

In this programming tutorial you will learn how to create div element in jquery. I always says that jquery is the best javascript library to deal with DOM's element. So let's see the following code snippet that will do what we want.

create div element in jquery

$("

hello world

").appendTo("body");
If you want to create div in other element of page then first select the parent element with something like
$("#id") or $(".class")
then use the .append() function.
$("#elementID").append("
hello world
")
So that's it. I love your feedback.
Read more...

Mozilla releases firefox 6.0

Mozilla releases firefox 6.0. Despite being less than two months old, Firefox 5 is now back at home. Mozilla released Firefox 6.0 on August 16, 2011. There are a number of bug-fixes in new version, also the list of new features is fairly lightweight.The latest version of Firefox has the following changes:

Whats new in firefox 6

  • Firefox 6 highlights a site’s domain in the address bar
  • Streamlined the look of the site identity block
  • Support for the latest draft version of WebSockets has been added with a prefixed API
  • Support for EventSource / server-sent events has been added.
  • Support for window.matchMedia has been added.
  • The new Scratchpad console allows developers to execute JavaScript code. It has access to every object and variable within the current page, but new Scratchpad variables won’t leak into it. The Scratchpad is similar to Firebug’s console command line, however, it doesn’t require the add-on and allows you to save snippets for later use. Moreover, if you like the Web Console, you’ll be pleased to know that it can be moved and docked elsewhere.
  • Usability of the Web Console has been improved
  • Added a new Web Developer menu item and moved development-related items into it
  • Improved the discoverability of Firefox Sync
  • Reduced browser startup time when using Panorama
  • Fixed several stability and security issues
Mozilla claim the new browser is 20% faster than Firefox 5. The speed gains will also be evident to Linux users.

More HTML5, CSS3 and DOM Support in Firefox 6
Web developers will able to adopt the following HTML5 technologies in Firefox 6:
  • CSS3 border-radius can be applied to iframes.
  • Text decorations such as underlines, overlines and strike-throughs can now be styled in CSS using -moz-text-decoration-line (none, underline, overline, line-through), -moz-text-decoration-style (inherit, solid, double, dotted, dashed, wavy) and -moz-text-decoration-color properties.
  • The progress tag for graphical progress bars has been added. Colors can be styled with the ::-moz-progress-bar pseudo-element.
  • Touch event support for touch-sensitive screens and trackpads has been included.
  • A new -moz-orient property allows you to set some elements, such as progress bars, to horizontal or vertical orientation.
  • The track element is supported so you can apply text tracks to native video and audio.
  • Using the window.matchMedia() method, the result of a media query string can be evaluated programmatically .
  • Custom data attributes (data-*) can now be accessed via the DOM’s element.dataset property.
  • Early support for Server-Sent Events has been implemented. This API permits push notifications from the server in the form of DOM events.
  • The new -moz-hyphens property lets you control how hyphenation of words is handled during line wrapping (none, manual, auto).
Read more...

Update records in database using 3-tier architecture in asp.net with c#

In this programming tutorial we will learn how to update records in database using 3-tier architecture in asp.net with c#. For beginners, I strongly recommend to read this tutorial 3-Tier Architecture in asp.net using c# first to get basics of three tier architecture in asp.net. So let’s begin, have a look over .aspx page
Update records in database using 3-tier architecture
Update records using three tier architecture in asp.net with c#.

view-users.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="view-users.aspx.cs" Inherits="view_users" %>
<!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> Update records in database using 3-tier architecture in asp.net with c#</title>
</head>
<body>
<form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server" EnableTheming="false" AutoGenerateColumns="false" GridLines="None" Width="100%" 
 OnRowEditing="GridView1_RowEditing">
        <Columns>
            <asp:TemplateField HeaderText="First Name" HeaderStyle-Width="20%" HeaderStyle-HorizontalAlign="Left">
                <ItemTemplate>
                    <asp:Label ID="lblFirstName" runat="server" EnableTheming="false" Text='<%# Bind("FirstName")%>'></asp:Label>
                </ItemTemplate>
                <ItemStyle HorizontalAlign="Left" />
            </asp:TemplateField>
           
	<asp:TemplateField HeaderText="Last Name" HeaderStyle-Width="20%" HeaderStyle-HorizontalAlign="Left">
                <ItemTemplate>
                    <asp:Label ID="lblLastName" runat="server" EnableTheming="false" Text='<%# Bind("LastName")%>'></asp:Label>
                </ItemTemplate>
                <ItemStyle HorizontalAlign="Left" />
           </asp:TemplateField>
			
	<asp:TemplateField HeaderText="Country" HeaderStyle-Width="20%" HeaderStyle-HorizontalAlign="Left">
                <ItemTemplate>
                    <asp:Label ID="lblCountry" runat="server" EnableTheming="false" Text='<%# Bind("Country")%>'></asp:Label>
                </ItemTemplate>
                <ItemStyle HorizontalAlign="Left" />
         </asp:TemplateField>
			
	<asp:TemplateField HeaderText="Age" HeaderStyle-Width="20%" HeaderStyle-HorizontalAlign="Left">
                <ItemTemplate>
                    <asp:Label ID="lblAge" runat="server" EnableTheming="false" Text='<%# Bind("Age")%>'></asp:Label>
                </ItemTemplate>
                <ItemStyle HorizontalAlign="Left" />
            </asp:TemplateField>
		   
            <asp:TemplateField HeaderText="Edit" HeaderStyle-Width="15%" HeaderStyle-HorizontalAlign="Center">
                <ItemTemplate>
                    <asp:Label ID="lblEdit" Visible="false" Text='<%# Bind("Id")%>' runat="server"></asp:Label>
                    <asp:ImageButton runat="server" ID="img_edit" ImageUrl="images/edit.gif" CommandName="Edit" />
                </ItemTemplate>
                <ItemStyle HorizontalAlign="Center" />
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
    <br />
    <div style="text-align: center;">
        &nbsp;
        <asp:Button ID="btnBack" runat="server" Style="font-size: 12px;" Text="Back" OnClientClick="history.back(-1); return false;" />
    </div>
</form>
</body>
</html>
As you have seen, we have an asp:gridview control in our web page. We have five template fields in it; these are FirstName, LastName, Country, Age and Edit image to update the records. The main things you must have to notice are the OnRowEditing event of gridview and label lblEdit that contains the primary key for updation of records, in this example lblEdit contains the value of Id column of users table. Through OnRowEditing event we will update the records in database. So let’s have a look over its c# code behind file.

view-users.aspx.cs
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
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 BusinessLayer;  //Don’t forget to include this namespace  

public partial class view_users : System.Web.UI.Page
{
    BusUsers _objUsers = new BusUsers();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
                //Binding gridview with records coming from database.
                BindGrid();
            
        }

    }
    public void BindGrid()
    {
        _objUsers.GetUsersRecords();
        // The table userrecords is a dynamically created table that we have
        // created in the BusUsers class. Userrecords table contains all the
        //records comes from database.
        GridView1.DataSource = _objUsers.UserDS.Tables["userrecords"];
        GridView1.DataBind();
    }

    #region Editing

    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
       //Getting index of currently selected row
        int index = e.NewEditIndex;
        GridViewRow row = GridView1.Rows[index];
        //The asp:Label just before the edit image button
        Label lbl = (Label)row.FindControl("lblEdit");
        int id = Convert.ToInt32(lbl.Text);
        // redirecting to next page with query string that will always contain a unique value
        Response.Redirect("edit-users.aspx?id=" + id + "");

    }
    #endregion
}
edit-users.aspx
Update records using 3-tier architecture
<table width="100%" cellpadding="2" cellspacing="2" border="0" align="left">
                      <tr id="trMessage" runat="server" visible="false">
                            <td style="color: Green;" colspan="2"><strong>The record has been updated successfully. </strong> </td>
                          </tr>
                      <tr>
                            <td width="15%" align="left" ><strong>FirstName</strong></td>
                            <td align="left">
                          <asp:TextBox ID="txtFirstName" runat="server" Font-Size="Small" Width="150px"></asp:TextBox>
                        </td>
                          </tr>
                      <tr>
                            <td align="left"><strong>Last Name</strong></td>
                            <td align="left"><asp:TextBox ID="txtLastName" runat="server" Font-Size="Small" Width="150px"></asp:TextBox>
                        </td>
                          </tr>
                      <tr>
                            <td align="left"><strong>Country</strong> </td>
                            <td align="left"><asp:TextBox ID="txtCountry" runat="server" Font-Size="Small" Width="150px"></asp:TextBox>
                        </td>
                          </tr>
                      <tr>
                            <td align="left"><strong>Age</strong> </td>
                            <td align="left"><asp:TextBox ID="txtAge" runat="server" size="5" Font-Size="Small"></asp:TextBox>
                        </td>
                          </tr>
                      <tr>
                            <td>&nbsp;</td>
                            <td align="left"><asp:Button ID="btnUpdate" runat="server" Text="Update" OnClick="btnUpdate_Click"/>
                          &nbsp;
                          <asp:Button ID="btnHistory" runat="server" Text="Back"
                                        OnClientClick="history.back(-1); return false;" />
                        </td>
                          </tr>
                    </table>
As you have seen we have four asp:TextBoxes in our page. The txtFirstName will contain the value of column FirstName in it, the txtLastName will contain the value of column LastName in it, the txtCountry will contain the value of column Country in it, and the txtAge will contain the value of column Age in it. We have also a hidden row, having id of trMessage in our page that will display the successful updating records message once every thing will go fine. Let’s have a look over its code behind file to know how these textboxes will contain values that will come from database and how all the records are updated when we will press the Update button available in our page.

edit-users.aspx.cs
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
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 BusinessLayer; //Don’t forget to declare this

public partial class edit_users : System.Web.UI.Page
{
    BusUsers _objUsers = new BusUsers();
    //Declare global variable id
    int id;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            id = Convert.ToInt32(Request.QueryString["id"]);
            //Getting records of users from database against id that we got from query string
            _objUsers.GetSelectedUserInfo(id);
            //[0] [0] means first column of first row return by query, which is FirstName
            // the first [0] indicated the row number, in this example we will have just one row
            //So we will always use the [0] for row number but column number will change respectively.
            txtFirstName.Text = _objUsers.UserDS.Tables["selected_user_info"].Rows[0][0].ToString();
            txtLastName.Text = _objUsers.UserDS.Tables["selected_user_info"].Rows[0][1].ToString();
            txtCountry.Text = _objUsers.UserDS.Tables["selected_user_info"].Rows[0][2].ToString();
            txtAge.Text = _objUsers.UserDS.Tables["selected_user_info"].Rows[0][3].ToString();
           
            
        }
    }
    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        
        id = Convert.ToInt32(Request.QueryString["id"]);
        // Calling function to update records in database
        _objUsers.UpdateUsers(id, txtFirstName.Text, txtLastName.Text, txtCountry.Text,Convert.ToInt32(txtAge.Text));
        // Show the successful message
        trMessage.Visible = true;
        // Redirects to the page after 5 seconds delay.
        Response.AddHeader("REFRESH", "5;URL=view-users.aspx");
    }
}
BusUsers.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using DataAccessLayer; //Don’t forget to import this namespace

namespace BusinessLayer
{
public class BusUsers
{
DbAccess _dbAccess = new DbAccess();
private DataSet _UserDS = new DataSet();
public DataSet UserDS
{
get
{
return _UserDS;
}
set
{
_UserDS = value;
}
}

        public void GetUsersRecords()
        {

            try
            {
                string strQuery = "select FirstName,LastName,Country,Age,id from web_tbl_users";
                if (_UserDS.Tables.Contains("userrecords"))
                {
                   _UserDS.Tables["studentrecords"].Clear();
                }
                _dbAccess.selectQuery(_UserDS, strQuery, "userrecords");
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

  //Function to get user records from database, in this example I used MS SQL SERVER as a backend database  
 
        public void GetSelectedUserInfo(int id)
        {

            try
            {
                string strGet = "select FirstName,LastName,Country,Age from web_tbl_users where id=" + id + "";
                if (_UserDS.Tables.Contains("selected_user_info"))
                {
                    _UserDS.Tables["selected_user_info"].Clear();
                }
                _dbAccess.selectQuery(_UserDS, strGet, "selected_user_info");
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

      //Function to get update records from database, in this example I used MS SQL SERVER as a backend database    
        public void UpdateUsers(int id, string firstName, string lastName, string country,int age)
        {
            try
            {
                string updateStrQuery = "update web_tbl_users set FirstName='" + firstName + "', LastName='" + lastName + "', Country='" + country + "', Age='" + age + "' where id='" + id + "'";
                _dbAccess.executeQuery(updateStrQuery);
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }


}

}
As far as DbAccess class is concerned, it is available in 3-Tier Architecture in asp.net using c#. DbAccess class is a single class that whole website uses to get connected with database. But we have multiple classes (Buses) in our BusinessLayer namespace (physically in BusinessLayer folder) depends upon our requirements.

Every thing is self explanatory and I will not go into further details as I already have written three tutorials 3-Tier Architecture in asp.net using c# , Insertion of records in database using 3-tier architecture in asp.net with c#,Delete records in database using 3-tier architecture in asp.net with c#. In case you have any confusion in BusUsers then read the comments in it or read the above mentioned tutorials to get the basics. So this is the way to update records in database using three tier architecture in asp.net with c#.

So that's it.
I love your feedback.
Read more...

ipad detection in asp.net with c#

In this programming tutorial we will learn how to detect whether request is from ipad or not in asp.net with c#. Ipad is getting popularity in market day by day due to its size and performance, so the web developer must check whether their website is working properly in ipad or not. There are certain things not working in ipad such as flash movies doesn't work in ipad, some css properties are not supported in ipad, so we have to write a code that will check whether the request is from ipad or not and then perform necessary actions. So let's have a look over the following code snippet.

ipad detection in asp.net with c#
if (Request.Headers["User-Agent"].ToLower().Contains("ipad"))
{
     //iPad detects. Write your logic here which is specific to iPad.
}
else
{
     //Normal browsers [from computers] requested.
}

OR
if(HttpContext.Current.Request.UserAgent.ToLower().Contains("ipad"))
{
     //iPad detects. Write your logic here which is specific to iPad.
}
else
{
     //Normal browsers [from computers] requested.
}

So that's it. It's pretty simple and need nothing to explain.
I love your feedback.
Read more...

Learn jquery from beginners to advanced level - part 1

In this programming tutorial we will learn jquery from beginners to advanced level.
Jquery is the widely used javascript library now and nowadays it is being widely used by web developers. So let's start.
What’s the problem with JavaScript?
JavaScript was an initially introduced in Netscape 2.0B3 in Dec 1995, a.k.a. Mocha, LiveScript, Jscript; however, its official name is ECMAScript.

JavaScript is a C-family, world’s worst named, extremely powerful language (not a script), totally unrelated to Java.

JavaScript is a weakly typed, classless, prototype based OO language that can also be used outside the browser. It is not a browser DOM.

The world’s most misunderstood programming language.

Browser DOM really sucks, and this is where jQuery comes to rescue.

Why use Javascript Libraries?

  • Cross browser javascript handling
  • Better selection and manipulation
  • Event binding and triggering
  • Ajax

Introduction to jQuery

A Quality of Life by jQuery:

$("#firstName").text("Joe Black");
$("button").click(function() {alert "Clicked";});
$(".content").hide();
$("#main").load("content.htm");
$("<div/>").html("Loading…").appendTo("#content");

Very compact and fluent programming model

What is jQuery?

jQuery is a lightweight, open-source JavaScript library that simplifies interaction between HTML and JavaScript.

It was and still being developed by John Resig from Mozilla and was first announced in January 2006.

It has a great community, great documentation, tons of plug-ins, and it was recently adopted by Microsoft.

A fast, concise, javascript library that simplifies how to traverse HTML documents, handle events, perform animations, and add AJAX.

– Concise (19 KB after minified and gzipped)
– Traverse HTML documents (selectors, traversing, manipulation )
– Events (binding and triggering events)
– Animation (predefined, UI)
– AJAX



The current version is 1.6.2 as of august 2011.

Getting Started

Download the latest version from http://jquery.com

To enable itellisense in VS 2008 SP1 install the –vsdoc hotfix:
VS90SP1-KB958502-x86.exe

VSDOC

Copy the jquery.js and the jquery-vsdoc.js into your application folder

VSDOC


Reference it in your markup

<script src="jquery.js"/>

jQuery Core Concepts

The Magic $() function

Create HTML elements on the fly

var el = $("<div/>")

Manipulate existing DOM elements

$(window).width()
Selects document elements (more in a moment…)

$("div").hide();
$("div", $("p")).hide();

Fired when the document is ready for programming.

$(function(){…});

Better use the full syntax:
$(document).ready(function(){…});

The full name of $() function is
jQuery("div");

It may be used in case of conflict with other frameworks/libraries. avoid jquery conflict with other javascript libraries

The library is designed to be isolated
(function(){
var 
jQuery=window.jQuery=window.$=function(){
// … 
};
})();

jQuery uses closures for isolation


Avoid $() conflict with other frameworks
var foo = jQuery.noConflict();
// now foo() is the jQuery main function
foo("div").hide();
// remove the conflicting $ and jQuery
var foo = jQuery.noConflict(true);


jQuery's programming philosophy is: GET >> ACT
$("div").hide()
$("<span/>").appendTo("body")
$(":button").click()
Almost every function returns in jQuery, which provides a fluent programming interface and chain-ability:
$("div").show().addClass("main").html("Hello jQuery");

Three Major Concepts of jQuery
1) The $() function
2) Get > Act
3) Chainability

jQuery Selectors

All Selector
$("*") 		// find everything

Selectors return a pseudo-array of jQuery elements

Basic Selectors
By Tag:
$("div") 
// <div>Hello jQuery</div>

By ID:
$("#usr")
// <span id="usr">John</span>

By Class:
$(".menu")	
// <ul class="menu">Home</ul>

Yes, jQuery implements CSS Selectors!

More Precise Selectors
$("div.main") 	// tag and class
$("table#data")	// tag and id

Combination of Selectors
// find by id + by class
$("#content, .menu")
// multiple combination
$("h1, h2, h3, div.content")


Hierarchy Selectors
$("table td") 		// descendants
$("tr > td") 		// children
$("label + input") 	// next
$("#content ~ div") 	// siblings

Selection Index Filters
$("tr:first")	// first element
$("tr:last")	// last element
$("tr:lt(2)") 	// index less than
$("tr:gt(2)") 	// index gr. than 
$("tr:eq(2)") 	// index equals

Visibility Filters
$("div:visible")	// if visible
$("div:hidden")	// if not


Attribute Filters
$("div[id]")			// has attribute
$("div[dir='rtl']")		// equals to
$("div[id^='main']") 	// starts with
$("div[id$='name']") 	// ends with
$("a[href*='msdn']") 	// contains



Forms Selectors
$("input:checkbox")	// checkboxes
$("input:radio")		// radio buttons
$(":button") 		// buttons
$(":text") 			// text inputs


Forms Filters
$("input:checked")	// checked
$("input:selected")	// selected
$("input:enabled")	// enabled
$("input:disabled")	// disabled


Find Dropdown Selected Item
<select name="cities">
<option value="1">Islamabad</option>
<option value="2" selected="selected">Tokyo</option>
<option value="3">London</option>
</select>

$("select[name='cities'] option:selected").val()

So that's it. Other parts of this tutorial series are coming soon. Stay tuned.

Read more...

Maintain scroll position on postback in asp.net

In this programming tutorial we will learn how to maintain scroll position on postback in asp.net. Normally when Postback is fired, the focus of page sets to the top position of the current page. User has to scroll down manually on the location of the web page where he was at last time before postback is fired.

Page.MaintainScrollPositionOnPostBack Property is used to get or set the position of page after Postback is fired.

Page.MaintainScrollPositionOnPostBack is supported in frameworks greater than equal to 2.0

You can add the following line on Page directive for a single page to maintain the previous scroll position on post back.
<%@ MaintainScrollPositionOnPostback="true" %>
Or you can add following line to the c# code behind of your asp.net page
Page.MaintainScrollPositionOnPostBack =true;
You can add following settings on Web.Config file for all pages of your website to maintain the previous scroll position when Postback is fired.
<configuration>
   <system.web>
      <pages maintainScrollPositionOnPostBack="true" />
   </system.web>
</configuration>

So that's it.
I Love your feedback.
Read more...

Count the number of parameters of a query string in asp.net using c#

In this programming tutorial you will learn how to count the number of parameters of a query string in asp.net using c#. Some times you may wanted to know how many parameters your query string contains so that you can implement appropriate checks in your code according to your requirement. In asp.net finding parameters are quite easy. Let's have a look over the code snippet given below

Count the number of parameters in a query string
protected void Page_Load(object sender, EventArgs e)
    {
       
        Int16 totalParameters;
        if (!Page.IsPostBack)
        {
            totalParameters = Request.QueryString.AllKeys.Length;
            Response.Write("The number of parameters the query string contains are "+totalParameters);
        }
     }

So that's it. The Request.QueryString.AllKeys.Length will give you what you want.
I love your feedback.
Read more...

Capitalize words in string using javascript

In this programming tutorial we will learn how to capitalize words in string using javascript. The functionality of prototype can be extended by appending a custom function after dot. Prototype object extends the objects which are inherit from base object. We can create our own extension and load these extension to our page or library. We can also give our file name like this Prototype.CapitalizeWords.js, Prototype.FormatCurrency.js. Let's have a look over the code snippet given below
Capitalize words in string using javascript

Copy/paste the following code in the <head> section of your page.

<script language="javascript" type="text/javascript">
String.prototype.toCapitalize = function()
{ 
   return this.toLowerCase().replace(/^.|\s\S/g, function(a) { return a.toUpperCase(); });
}
//And this is the way to call the toCapitalize() function
alert("Muhammad Ali".toCapitalize());

alert("ADEEL FAKHAR".toCapitalize());

alert("shoaib akhtar".toCapitalize());

</script>

So that's it.
I love your feedback.
Read more...