Uppercase and lowercase strings using jquery

In this programming tutorial we will learn how to convert strings in uppercase and lowercase using jquery. It is not a difficult task in jquery. Jquery has two built-in functions for handling these two cases. Those two functions are .toUpperCase() and .toLowerCase(). Let's have a look over the example given below that demonstrates how to do so.
Convert string in uppercase
var name="Adeel Fakhar";//Very simple
var nameUpperCase=name.toUpperCase(); 

Output
ADEEL FAKHAR

Convert string in lowercase
var name="Adeel Fakhar";
var nameLowerCase=name.toLowerCase(); //Very simple

Output
adeel fakhar

So that's it. I hope you will find this tutorial very useful.

Stay tuned with nice-tutorials.blogspot.com for bundle of jquery tutorials.

I love your feedback.
Read more...

Add new item in dropdown using jquery

In this programming tutorial we will learn how to add new item in dropdown using jquery. It is quite easy in jquery. Let's have a look over the code snippet given below in which i will add a new country in dropdown when button is clicked.
Add new item in dropdown using jquery
before

After
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Add new item in dropdown using jQuery</title>
    <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.2.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
            $("#btnClick").click(function () {
                var newCountry = $("#txtItem").val();
                if (newCountry.length > 0)
                    {
                    $("#ddlCountry").append($("<option>").val(newCountry).text(newCountry));
                    $("#txtItem").val("");
                   }
            });
        });
    </script>
</head>
<body>
    <div style="font-family:verdana;font-size:12px;">
   New Country: <input type="text" id="txtItem" />
 Country:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;
 <select id="ddlCountry">
 <option value="Pakistan">Pakistan</option>
 <option value="China">China</option>
 <option value="United States">United States</option>
 </select>
        <input id="btnClick" type="button" value=" Add Country " />
    </div>
</body>
</html>

In this above mentioned example, i have a textbox, a dropdown and a button in my page. Country dropdown by default contains three countries which are Pakistan, China and United States. Now for adding new country such as Australia or india, i have written a code in document.ready(), that will execute when button's click event will be fired.
$("#ddlCountry").append($("<option>").val(newCountry).text(newCountry));
The above mentioned code snippet will dynamically add new item or in this example we can say new country to the dropdown using append() function of jquery, which is a built-in function in jquery.

So that's it. This is the way to add new item or element in dropdown using jquery.
I love your feedback.
Read more...

Install php on windows server 2008 R2

In this programming tutorial we will learn how to install php on windows server 2008 R2. Couple of weeks ago one of my colleague asked me to install php on windows server 2008 R2 as he had to deploy a website and I have done it successfully without any problem. Let’s have a look over how to accomplish our task.
Simply go to this tutorial Install PHP on Windows 7 with IIS 7 via FastCGI and that's it. You just have to repeat the steps that you have performed on Windows 7 in order to accomplish this task.

Note:-
Depending on your location you can set a specific date.timezone value by setting the date.timezone property in php.ini file:
date.timezone = "US/Central"

Don't forget to uncomment the date.timezone by removing its preceding semicolon.

So that's it.
Your feedback gives me energy.
Read more...

Learn jquery from beginners to advanced level - part 3 (Final Part)

Finally I am writing the third and last tutorial of this tutorial series. Again I am saying if you are new visitor and haven't read my first two tutorial of this series then please read those tutorials first. Click to read Part 1 and click to read Part 2. One thing I want to ensure you is that if you read and understand all of these three tutorials then you can say yourself the expert of jquery, and you can do any task in jquery with minimum effort. Ok. Now let's start right from there, where we were.
Events

When the DOM is ready…

$(document).ready(function(){
 //Your code will come here
});

  • Fires when the document is ready for programming.
  • Uses advanced listeners for detecting.
  • window.onload() is a fallback.

Attach Event

// execute always
$("div").bind("click", fn);
// execute only once
$("div").one("click", fn);

Possible event values:

blur, focus, load, resize, scroll, unload, beforeunload, click, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, error (or any custom event)

jQuery.Event object
Detaching Events
$("div").unbind("click", fn);

(Unique ID added to every attached function)

Events Triggering
$("div").trigger("click");

Triggers browser’s event action as well. Can trigger custom events. Triggered events bubble up.

Events Helpers
// attach / trigger
elem.blur(fn) / elem.blur()
elem.focus(fn) / elem.focus()
elem.click(fn) / elem.click()
elem.change(fn) / elem.change()

And many others…

Preventing Browser Default Action
// use different triggering function
$("div").triggerHandler("click");

// prevent default action in handler
function clickHandler(e) {
 e.preventDefault();
}

// or just return false
function clickHandler(e) {return false;}

Preventing Bubbling
// stop bubbling, keep other handler
function clickHandler(e) {
 e.stopPropagation();
}

// stop bubbling and other handlers
function clickHandler(e) {
 e.stopImmediatePropagation();
}

// or just return false
function clickHandler(e) {return false;}

Live Events (Attach events to dynamically created elements)
// attach live event
("div").live("click", fn);
// detach live event
("div").die("click", fn);

Currently supported events:

click, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, keydown, keypress, keyup

Effects

Showing or Hiding Element
// just show
$("div").show();
// reveal slowly, slow=600ms
$("div").show("slow");
// hide fast, fast=200ms
$("div").hide("fast");
// hide or show in 100ms $(“div”).toggle(100);

Sliding Elements
$("div").slideUp();
$("div").slideDown("fast");
$("div").slideToggle(1000);

Fading Elements
$("div").fadeIn("fast");
$("div").fadeOut("normal");
// fade to a custom opacity
$("div").fadeTo ("fast", 0.5);

Fading === changing opacity

Detecting animation completion
$("div").hide("slow", function() {
  alert("The DIV is hidden");
});

$("div").show("fast", function() {
  $(this).html("Hello jQuery");
}); // this is a current DOM element 

Every effect function has a (speed, callback) overload

Custom Animation
// .animate(options, duration)
$("div").animate({
    width: "90%",
    opacity: 0.5,
    borderWidth: "5px"
     }, 1000);

Chaining Animation
$("div").animate({width: "90%"},100)
  .animate({opacity: 0.5},200)
  .animate({borderWidth: "5px"});

By default animations are queued and than performed one by one

Controlling Animations Sync
$("div")
 .animate({width: "90%"},
      {queue:false, duration:1000})
 .animate({opacity : 0.5});

The first animation will be performed immediately without queuing

AJAX with jQuery

Loading content
$("div").load("content.htm");
// passing parameters
$("#content").load("getcontent.aspx",
     {"id":"33","type":"main"});

Sending GET/POST requests
$.get("test.aspx", {id:1},
  function(data){alert(data);});

$.post("test.aspx", {id:1},
  function(data){alert(data);});

Retrieving JSON Data
$.getJSON("users.aspx", {id:1},
  function(users)
  {
   alert(users[0].name);
  });

Retrieving JS Files
$.getScript("script.js",
  function()
  {
   doSomeFunction();
  });

Extending the Library

Adding Methods
// definition
jQuery.fn.printLine = function(s) {
 return jQuery(this).each(function() {   this.append("<div>"+ s +"</div>");
 });
};
// usage
$("#log").printLine("Hello");

Closure to solve the $ issue
(function ($) {
  jQuery.fn.printLine = function(s) {
 return $(this).each(function() {    this.append("<div>"+ s +"</div>");
 });
};
})(jQuery);

Custom Selectors
$.expr[‘:’].test = function(o, i, m, s) {
// o – current object in the selection
// i – loop index in the stack
// m – meta data about your selector
// s – stack of all the elements
// return true to include the element
// return false to exclude the element
};

So that's it. I tried my level best to teach you jquery from beginners to advanced level in this series of tutorials. Now just you have to practice more and more to get a grip on jquery.

I love your feedback.
Read more...

Learn jquery from beginners to advanced level - part 2

In this programming tutorial we will learn jquery from beginners to advanced level. If you are new visitor and haven't read my first tutorial of this series then first please read the tutorial Learn jquery from beginners to advanced level - part 1. Ok. Now let's start right from there, where we were.
Selectors demo

Document Traversal

A Selector returns a pseudo array of jQuery objects
$(“div”).length

Returns number of selected elements. It is the best way to check selector.

Getting a specific DOM element

 $(“div”).get(2) or $(“div”)[2]

Returns a 2nd DOM element of the selection

Getting a specific jQuery element

$(“div”).eq(2)

Returns a 2nd jQuery element of the selection

each(fn) traverses every selected element calling fn()
var sum = 0;
$(“div.number”).each(
		function(){
		  sum += (+this.innerHTML);
		});

this – is a current DOM element

each(fn) also passes an indexer

$(“table tr”).each(
	function(i){
		if (i % 2) 
			$(this).addClass(“odd”);
	});

$(this) – convert DOM to jQuery i - index of the current element

Traversing HTML
.next(expr) 	// next sibling

.prev(expr)		// previous sibling

.siblings(expr)	// siblings

.children(expr) // children

.parent(expr) 	// parent

Check for expression
$(“table td”).each(function() {
	if ($(this).is(“:first-child”)) {
		$(this).addClass(“firstCol”);
	}
}); 

Find in selected
// select paragraph and then find 
// elements with class ‘header’ inside 
$(“p”).find(“.header”).show();

 // equivalent to:
$(“.header”, $(“p”)).show();

Advanced Chaining
$(“<li><span></span></li>”) // li
	.find(“span”) // span
		.html(“About Us”) // span 
		.andSelf() // span, li
			.addClass(“menu”) // span,li 
		.end() // span 
	.end() // li 
	.appendTo(“ul.main-menu”);

Get Part of Selected Result
$(“div”).slice(2, 5).not(“.green”).addClass(“middle”);

HTML Manipulation

Getting and Setting Inner Content
$(“p”).html(“<div>Hello World!</div>”);

// escape the content of div.b
$(“div.a”).text($(“div.b”).html());

Getting and Setting Values
// get the value of the checked checkbox
$(“input:checkbox:checked”).val();

// set the value of the textbox
$(“:text[name=‘txt’]”).val(“Hello”);

// select or check lists or checkboxes
$(“#lst”).val([“NY”,”IL”,”NS”]);

Handling CSS Classes
// add and remove class
$(“p”).removeClass(“blue”).addClass(“red”);

// add if absent, remove otherwise
$(“div”).toggleClass(“main”);

// test for class existance
 if ($(“div”).hasClass(“main”)) { 
// Your code will come here

}

Inserting new Elements
// select > append to the end
$(“h1”).append(“<li>Hello World</li>”);

// select > append to the beginning
$(“ul”).prepend(“<li>Hello World</li>”);

// create > append/prepend to selector

$(“<li/>”).html(“9”).appendTo(“ul”);

$(“<li/>”).html(“1”).prependTo(“ul”);

Replacing Elements
// select > replace
$(“h1”).replaceWith(“<div>Hello</div>”);

// create > replace selection
$(“<div>Hello</div>”).replaceAll(“h1”);

Replacing Elements while keeping the content
$(“h3”).each(function(){
	$(this).replaceWith(“<div>” + $(this).html() 
					+ ”</div>”);
	});

Deleting Elements
// remove all children
$(“#mainContent”).empty();

// remove selection
$(“span.names”).remove();

// change position
$(“p”).remove(“:not(.red)”).appendTo(“#main”);

Handling attributes
$(“a”).attr(“href”,”home.htm”);
// <a href=“home.htm”>…</a>

// set the same as the first one
$(“button:gt(0)”).attr(“disabled”,$(“button:eq(0)”).attr(“disabled));
// remove attribute - enable
$(“button”).removeAttr(“disabled”)	

Setting multiple attributes
$(“img”).attr({
		“src” : “/images/smile.jpg”,
		“alt” : “Smile”,
		“width”  : 10,
		“height” : 10
});

CSS Manipulations
// get style
$(“div”).css(“background-color”);

// set style 
$(“div”).css(“float”, “left”);

// set multiple style properties
$(“div”).css({“color”:”blue”,
			 “padding”: “1em”
			 “margin-right”: “0”,
			 marginLeft: “10px”});

Dimensions
// get window height
var winHeight = $(window).height();

// set element height
$(“#main”).height(winHeight);

//.width() – element
//.innerWidth() – .width() + padding

//.outerWidth() – .innerWidth() + border
//.outerWidth(true) – including margin

The default unit is Pixel (px)

Positioning
// from the document
$(“div”).offset().top;

// from the parent element
$(“div”).position().left; 

// scrolling position
$(window).scrollTop(); 

So that's it, i try my level best to let you learn jquery from beginners to advanced level with small and handy examples. Third and Final part of this tutorial series will come soon. Stay tuned.

Your feedback always provides me lot of energy.
Read more...

ASP.NET HyperLink - Set alt tag of the image

In this programming tutorial we will learn how to set the alt tag of an image that has been set by asp.net hyperlink using its ImageUrl property which is

HyperLink.ImageUrl

Couple of days ago i am working over a project in which i am fixing the issues reported by SEO Tool Kit (use for site analysis) which is installed in IIS 7 (You can Install it in IIS 5 and IIS 6 as well). The SEO Tool kit is very much helpful if you want to check the errors and violations of the website that are damaging the ranking of your website or specific web pages in the search engine, especially in google. I got lot of violations about alt tag is missing, when i was fixing all these violations then i got an asp:Hyperlink that contains an image which alt tag was missing, i checked all the possible properties of the asp:hyperlink to give alt tag to the image, like ToolTip property but i was fail to achieve what i want, moreover the HyperLink control doesn't have an AlternateText property.
Then surfing the internet i got the solution and it was quite easy and surprised to me. The solution was to give text between starting and ending tag of the asp:hyperlink and then that text will become the alt of the image, like given below
<asp:HyperLink ID="HyperLink1" runat="server" ImageUrl="~/Images/proceed.gif" 
                        NavigateUrl="~/Welcome.aspx">Proceed

So that's it. The word Proceed will become the alt tag of the image located inside the hyperlink.

Stay tune with nice-tutorials.blogspot.com because in future i will write very informative and detailed tutorials about SEO Tool kit, which is used for analysis of website to improve its ranking in the major search engines. Also i will tell you how to deploy a website in windows 2008 R1, you can then open your own hosting company as well if you have servers that are capable to run the websites :). But still bottom line is to stay tune with nice-tutorials.blogspot.com

Do comment. Your feedback gives me energy.
Read more...

spell checker in jquery using php

In this programming tutorial we will learn how to perform spell checking in jquery using php. For this i will use a jquery plugin which is called jquery-spellchecker. By god, i have tried many spell checkers but there are lot of problems in them, some spell checkers that i like was not free of cost, some was not cross browser compatible then i found this spell checker which is pretty good. This jQuery plugin is used to check the spelling of a chunk of text, using google's spell checking service. The plugin also gives you the option of using pspell. If you are able to use pspell then you will have great control over your dictionary to manage spells of words. To communicate with google's api or pspell, php will be used.
The plugin comes with 2 default behaviours:
  • If bound to a HTML element other than textarea, the plugin will highlight the incorrectly spelt words. Clicking on those incorrect words will bring up the suggest box.
  • If bound to a textarea element, the plugin will add the incorrectly spelt words after the textarea. Clicking on those incorrect words will bring up the suggest box.

Server side script
As i told you above, the plugin uses PHP script that supports two type of spell checking engines: php's pspell extension for aspell, or google's spell checking services (API).

using pspell requires you to have aspell installed on the server, as well as the PHP pspell extension using google requires minimal server adjustments.
Note:-

The example PHP file uses the json_encode function, which requires the json package. This package comes default with PHP 5 >= 5.2.0. If you have an older version of PHP then you can install this package via PECL, or use a custom json library.

If you would like to use a different server side language, let's suppose asp.net then wait for my next tutorial, i have working example of this plugin with asp.net, jquery and google's spell checking api in my system and soon it will be uploaded in the form of tutorial.

Check chunk of text:-


checkspelling.php?engine=pspell
Request:
Content type: application/x-www-form-urlencoded;charset=UTF-8
Data: text="a chunk of text without any punctuation"
Response:
Content type: application/json
Example response: ["bbad","speltt","wwords"]
Get suggestions for a word:

checkspelling.php?engine=pspell

Request:
Content type: application/x-www-form-urlencoded;charset=UTF-8
Data: suggest="word"
Response:
Content type: application/json
Example response: ["suggest","snuggest","soggiest"]


Supported languages

Pspell

What is pspell??? Good question, ok :) Pspell is simply a php wrapper to the GNU aspell spell checker. So supporting large range of languages is as easy as installing the relevant aspell language dictionary. These dictionary packs are available in most GNU/Linux distro repositories. In debian/ubuntu, you can install a new dictionary in a following way:
sudo apt-get install aspell-LANG
(you have to replace LANG with the language code)

If you want to search for a particular language dictionary then you can use apt-cache:
sudo apt-cache search aspell


or view the aspell supported languages page.

Don't forget to restart apache after successfully installation of new dictionaries. If you having problems getting pspell to work with personal dictionaries, view the php errors!

Note:- Aspell also works like charm in windows

Google API
I couldn't find any information for the languages google supports, but probably there are lot of languages and in my next tutorial you will see that i will use asp.net with google api to perform spell checking via this jquery plugin.

Usage
Include the following in the head section of your html document:
<link href="css/spellchecker.css" media="screen" rel="stylesheet" type="text/css"></link>
<script src="js/jquery.js" type="text/javascript">
</script>
<script src="js/jquery.spellchecker.js" type="text/javascript">
</script>

Defaut usage
// initiate the spell checker on an element, fire the 'check' function
$("textarea#text-content").spellchecker("check");

Plugin options: (all optional)
$("textarea#text-content")
.spellchecker({
        url: "checkspelling.php",       // default spellcheck url
        lang: "en",                     // default language 
        engine: "pspell",               // pspell or google
        addToDictionary: false,         // display option to add word to dictionary (pspell only)
        wordlist: {
                action: "after",               // which jquery dom insert action
                element: $("#text-content")    // which object to apply above method
        },      
        suggestBoxPosition: "below",    // position of suggest box; above or below the highlighted word
        innerDocument: false            // if you want the badwords highlighted in the html then set to true
});

You only want to execute the above code after an event has occured:
// initiating the spell checker is not necessary if using the default plugin options
$("a.check-spelling").click(function(e){
        e.preventDefault();
        $("textarea#text-content").spellchecker("check");
});

This jquery plugin will fire off a callback function after it has finished checking words:
$("a.check-spelling").click(function(e){
        e.preventDefault();
        $("textarea#text-content").spellchecker("check", function(result){
                // if result is true then there are no incorrectly spelt words
                if (result) alert('There are no incorrectly spelt words.');
        });
});

And for removing all spellchecker html, just do the following:
$("textarea#text-content").spellchecker("remove");


Source
jquery.spellchecker

Simple Demo
Demo

So that's it. I hope you will love this spell checker in jquery using php.
I love your feedback.
Read more...