How to handle checkbox using jQuery

Monday, August 29, 2011

Checkbox is one of most used form element in web. It is used to define the state like on or off. We generally need to modify its state in response to client event. For this jQuery is very handy to manipulate the state of checkbox. jQuery is a javascript framework for simplifying javascript coding. There are several ways to find out if the checkbox is checked or not using jQuery
$('input[name=foo]').is(':checked')
$('input[name=foo]').attr('checked')
The state of the checkbox can be changed by changing the attribute 'checked' by using 'attr' method of jQuery.
For checked state:
$('input[name=foo]').attr('checked', true);

To uncheck the checkbox:
$('input[name=foo]').attr('checked', false);
Demo
Let us take an example HTML form.

<p><a href="#" id="btn_all">ALL</a>&nbsp;<a href="#" id="btn_none">NONE</a>&nbsp;<a href="#" id="btn_reverse">REVERSE</a></p>
<form action="" method="post" name="form1" id="form1">
  <table width="100%" border="0" cellspacing="0" cellpadding="0">
    <tr>
      <td width="25"><input name="ch1" id="ch1" type="checkbox" value="A" /></td>
      <td>First</td>
    </tr>
    <tr>
      <td><input name="ch2" id="ch2" type="checkbox" value="B" /></td>
      <td>Second</td>
    </tr>
    <tr>
      <td><input name="ch3" id="ch3" type="checkbox" value="C" /></td>
      <td>Third</td>
    </tr>
    <tr>
      <td><input name="ch4"  id="ch4" type="checkbox" value="D" /></td>
      <td>Fourth</td>
    </tr>
    <tr>
      <td><input name="ch5" id="ch5" type="checkbox" value="E" /></td>
      <td>Fifth</td>
    </tr>
  </table>
</form>

We have three links which we will treat as buttons for selecting all, deselecting all and reversing the status. Below is the javascript code for the purpose.

jQuery(document).ready(function($){
 //
 $('#btn_all').click(function(e){
  e.preventDefault();
  $("#form1 input:checkbox").attr("checked",true)
 });
 //
 $('#btn_none').click(function(e){
  e.preventDefault();
  $("#form1 input:checkbox").attr("checked",false)
 });
 //

 $('#btn_reverse').click(function(e){
  e.preventDefault();
  $("#form1 input:checkbox").each(function(){
   this.checked=!this.checked;
  });
 });

});

Demo

10+ Most Essential Firefox Addons For Developers

Firefox Addon is most amazing feature in Mozilla Firefox browser. We can find plenty of Firefox Addons to enhance the functionality of the browser. Nowadays, for developer, we cannot even imagine their work without Firefox and its addons. Here is the list of 10+ most essential Firefox addons in random order.
10+ Most Essential Firefox Addons For Developers
Firefox
  1. Firebug
    Firebug integrates with Firefox to put a wealth of development tools at your fingertips while you browse. You can edit, debug, and monitor CSS, HTML, and JavaScript live in any web page.
  2. Web Developer Toolbar
    The Web Developer extension adds a menu and a toolbar to the browser with various web developer tools.
  3. FireFTP
    FireFTP is a free, secure, cross-platform FTP client for Mozilla Firefox which provides easy and intuitive access to FTP servers.Along with transferring your files quickly and efficiently, FireFTP also
    includes more advanced features such as: directory comparison, syncing directories while navigating, SFTP, SSL encryption, search/filtering, integrity checks, remote editing, drag & drop, file hashing, and much more!
  4. ShowIP
    ShowIP addon show the IP address(es) of the current page in the status bar. It also allows querying custom nformation services by IP (right mouse button) and hostname (left mouse button), like whois, netcraft.
    Additionally you can copy the IP address to the clipboard.
  5. Greasemonkey
    Greasemonkey allows you to customize the way a webpage displays using small bits of JavaScript.
  6. ColorZilla
    Colorzilla contains Advanced Eyedropper, ColorPicker, Page Zoomer and other colorful goodies. With ColorZilla you can get a color reading from any point in your browser, quickly adjust this color and paste it into another program. You can Zoom the page you are viewing and measure distances between any two points on the page. The built-in palette browser allows choosing colors from pre-defined color sets and saving the most used colors in custom palettes. DOM spying features allow getting various information about DOM elements quickly and easily.
  7. Pixlr Grabber
    Pixlr Grabber is one useful tool to grab images from the web. Making screen grabs and pulling down images from the web just got a bit more easy. With the Pixlr grabber add-on you can choose to Edit, Share, Save or Copy your final grabs. You also get the possibility to right-click any image or background to edit them.
  8. FoxyProxy
    FoxyProxy is a Firefox extension which automatically switches an internet connection across one or more proxy servers based on URL patterns. Put simply, FoxyProxy automates the manual process of editing Firefox's Connection Settings dialog. Proxy server switching occurs based on the loading URL and the switching rules you define.
  9. YSlow
    YSlow analyzes web pages and suggests ways to improve their performance based on a set of rules for high performance web pages. YSlow is a Firefox add-on integrated with the Firebug web development
    tool. YSlow grades web pagebased on one of three predefined ruleset or a user-defined ruleset. It offers suggestions for improving the page's performance, summarizes the page's components, displays statistics about the page, and provides tools for performance analysis, including Smush.it and JSLint.
  10. Seoquake
    Seoquake is a Mozilla Firefox SEO extension aimed primarily at helping web masters who deal with search engine optimization (SEO) and internet promotion of web sites. Seoquake allows to obtain and
    investigate many important SEO parameters of the internet project under study on the fly, save them for future work, compare them with the results, obtained for other, competitive, projects.
  11. IE View
    IE View lets you load pages in IE with a single right-click, or mark certain sites to *always* load in IE. Useful for incompatible pages, or cross-browser testing.
  12. iMacros
    iMacros was designed to automate the most repetitious tasks on the web. If there's an activity you have to do repeatedly, just record it in iMacros. The next time you need to do it, the entire macro will run at
    the click of a button! With iMacros, you can quickly and easily fill out web forms, remember passwords, create a webmail notifier, download information from other sites, scrape the Web (get data from multiple sites), and more. You can keep the macros on your computer for your own use, or share them with others by embedding them on your homepage, blog, company Intranet or any social bookmarking service.

XML Generator PHP Class – Generates XML from MySQL table

Sunday, August 28, 2011

The XMLgen class provide an easy way to create XML file from the MySQL table.

License of this source code is 'Do Whatever You Want' :P

Please feel free to improve this code. And dont forget to inform me. :-)
<?php
/*
 * The XMLgen class provide an easy way to create XML file from the MySQL table. 
 * 
 * License of this source code is 'Do Whatever You Want' :P
 * Please feel free to improve this code. And dont forget to inform me. :-)
 *
 * About Me:
 * Nilambar Sharma 
 * Kathmandu, Nepal
 * URL: http://ernilambar.blogspot.com
 * Twitter: http://twitter.com/nilambar
 *
 * Example:
 *
 * database
 *  |  id   |  title  | URL  |
 *  |  1  | Google  | http://www.google.com  |
 *  |  2  | Hotmail  | http://hotmail.com  |
 *
 * XML file
 *
 * <?xml version="1.0" encoding="UTF-8"?>
 * <root>
 * <links>
 * <id>1</id>
 * <title>Google</title>
 * <URL>http://www.google.com </URL>
 * <id>2</id>
 * <title>Hotmail</title>
 * <URL>http://hotmail.com</URL>
 * </links>
 * </root>
 *
 *
 * Cheers!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
 */
class XMLgen
{
	var $_table_name;	//table name
	var $_db_name;		//database name
	var $_host;			//database host
	var $_username;		//username
	var $_pass;			//password
	var $_filename;		//xml file name
	var $_header;		//xml header
	var $_op;			//xml output
	var $_main_tag;		// main tag in xml
	var $_sub_tag;		//sub tag in xml
	//////////////////////////////////////////////
	/**
     * Constructor 
     * 
     */
	function XMLgen()
	{
		$this->_header="<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
		$this->_op='';
		$this->_op.=$this->_header;
	}
	/**
     * Prepare necessary database connection; connect to the database host and select the database
	 * takes 4 parameters
	 * $host = database host
     * $user = database user name
	 * $pass = password for database user
	 * $dbname = database name
	 * 
     */
	function xmlmysqlconnect($host,$user,$pass,$dbname)
	{
		$this->_host=$host;
		$this->_username=$user;
		$this->_pass=$pass;
		$this->_db_name=$dbname;

		$con = mysql_connect($this->_host,$this->_username,$this->pass);
		if (!$con)
		{
			die('Could not connect: ' . mysql_error());
		}
		else
		{
			$sel=mysql_select_db($this->_db_name,$con);
			if(!$sel)
			{
				die('Could not select database: ' . mysql_error());
			}
		}
	}
	/**
     * generates xml file getting data from the table
	 * takes 4 parameters
	 * $table_name = table name from which you want to create XML
     * $filename = XMl file name
	 * $main_tag = the root tag of XML
	 * $sub_tag = child tag of $main_tag
	 * 
     */
	function dbtoxml($table_name,$filename,$main_tag,$sub_tag)
	{
		$this->_table_name=$table_name;
		$this->_filename=$filename;
		$this->_main_tag=$main_tag;
		$this->_sub_tag=$sub_tag;
		//////
		$this->_op.="<".$this->_main_tag.">";
		//
		$sql="SELECT * FROM ".$this->_table_name;
		$result = mysql_query($sql);

		$i = 0;
		while($i<mysql_num_fields($result))
		{
		  $meta=mysql_fetch_field($result,$i);
		  $keyarray[]=$meta->name;
		  $i++;
		} 
		//print_r($keyarray);
		while($row = mysql_fetch_array($result))
		{
			$this->_op.="<".$this->_sub_tag.">";
			//
			for($i=0;$i<count($keyarray);$i++)
			{
				$this->_op.="<".$keyarray[$i].">";
				$this->_op.=$row[$i];
				$this->_op.="</".$keyarray[$i].">";
			}
			//
			$this->_op.="</".$this->_sub_tag.">";
		}
		///
		$this->_op.="</".$this->_main_tag.">";
		//finish retriving from db
		//write to file
		$fh=fopen($this->_filename,"w") or die("can't open file"); 
		$wflag=fwrite($fh,$this->_op);
		if(!$wflag)
		{
			echo "Cannot create a XML file: <b>" . $this->_filename . "</b>";
		}
		fclose($fh);
	}
}
?>

jQuery’s getJSON function to retrieve data in JSON format; Same domain or cross-domain request

Thursday, August 25, 2011

Today I want to share the problems I faced and its solution about using JSON with jQuery. JSON is a lightweight text-based open standard designed for human-readable data interchange. It is being popular nowadays and it has been used by some popular sites like Twitter. jQuery is one of the most popular javascript framework. jQuery has got Ajax function. It perform an asynchronous HTTP (Ajax) request. For working with JSON, we can use either $.ajax function with 'dataType' parameter as 'json' or simply use $.getJSON function. In the example I have used $.getJSON for simplicity.
First lets create a client page. In html part. We keep a div with certain id where our ajax returned data will be replaced. Now in scripting part we use getJSON function. Assumed you have already included jQuery library file.
javascript code
<script type="text/javascript">
jQuery(document).ready(function($){
 $.getJSON('http://nilambar.com.np/test/converterapi/converterapi.php?callback=?',
  function(result){
   var op='';
   op+= '<p>';
   op+=' '+result.mday;
   op+=' '+result.month;
   op+=' '+result.year;
          op+='   '+result.hours;
   op+=':'+result.minutes;
   op+='<p>';
   $('#opid').html(op);
  });
});
</script>
getJSON takes three parameters. One is url from where we are going to fetch. Second is the data to be sent and third parameter is callback function which would be executed if request is successful. You may be thinking why there is 'callback=?' in the url. This is used to treat the request as JSONP instead. JSON only allows the request under same domain whereas JSONP also supports cross-domain request.
Now lets setup our server page.Here is the example php page.
<?php
date_default_timezone_set('Asia/Katmandu');
$json_encoded=json_encode(getdate());
$callback=$_GET['callback'];
$op=$callback.'('.$json_encoded.')';
header('Content-type: text/html');
echo $op;
?>
In server we need to echo our data in JSON format. PHP has 'json_encode' function which can convert array into json encoded form. In the example, I have fetched current date & time and it is json encoded. There is little hack in the code. jQuery excepts the returned data as callbackFunction(json_data). This callbackFunction is automatically replaced in ? by jQuery while requesting. Here header content type is 'text/html' . I tried with 'application/json' but it gives error 'invalid label' in firebug. So I tried 'text/html' and it
works perfect.
You can get twits from Twitter in JSON format. Use following url in $.getJSON function in jQuery. You need to replace USERNAME with your desired twitter screenname.
http://twitter.com/status/user_timeline/USERNAME.json?count=10&callback=?

Empty directory recursively in PHP

Wednesday, August 24, 2011


Sometime we need to delete all contents in the directory whether it is any files or directory. At that time this function will be handy to fulfill our need. It empties the folder recursively, that means all the folders ans sub-folders are removed. Two parameters are passed in the function, First one is the directory to be emptied and second one is the flag to determine whether to delete the given folder.
If set 'true', given folder is also removed at last. If emptying is our need then you should pass 'false'.
function emptyDirectory($dirname,$self_delete=false) {
   if (is_dir($dirname))
      $dir_handle = opendir($dirname);
   if (!$dir_handle)
      return false;
   while($file = readdir($dir_handle)) {
      if ($file != "." && $file != "..") {
         if (!is_dir($dirname."/".$file))
            @unlink($dirname."/".$file);
         else
            emptyDirectory($dirname.'/'.$file,true);
      }
   }
   closedir($dir_handle);
   if ($self_delete){
        @rmdir($dirname);
   }
   return true;
}

How to add Favicon in your WordPress site

What is a Favicon ?
A favicon is a small … 16px by 16px … image. Your favicon usually appears right before your web site name in the browser location bar, in browser tabs, in browser favorites, in RSS readers, and the like.
A favicon (short for favorites icon), also known as a website icon, shortcut icon, url icon, or bookmark icon is a 16×16,32×32 or 64×64 pixel square icon associated with a particular website or webpage.
Why do I want one?
Favicons can help identify your web site or blog across the Internet. These images become increasingly useful the more people use RSS readers and tabbed browsing. It offers the reader a visual reference allowing them to quickly identify your web site.
Step 1:Create Favicon
Your favicon image must be a .ico . This can pose a little bit of a problem as some desktop image programs do not allow for the saving of images in the .ico format. If this is the case with your program, you can can save your image as a .GIF, .JPG, or .PNG and then use an online conversion program. You can create a 100 x 100 image, for example, and the conversion program will also shrink your image. I generally use Dynamic Drive conversion tool. ( Favicon Generator ) You can also find many different programs that allow you to create a favicon online.
Step 2: Upload you Favicon
Using your favorite FTP program or CPanel, upload your favicon to your WordPress theme's main folder. For example, if your theme is 'mytheme' then …/wp-content/themes/mytheme/
Step 3: Link your Favicon
Now in your theme folder open header.php in your favorite editor and add following line in between <head>and </head>
<link rel="shortcut icon" 
href="<?php bloginfo(stylesheet_directory); ?>/favicon.ico" />

How to use javascript replace() method

In Javascript, there is a handy function replace() for String Object. We can easily replace the sub-string with new string and also regular expression in available. Replace may be case-sensitive or case insensitive. Also global replacement can be obtained using this function.
Syntax
string.replace(regex/substring,replacetext)
replace() function takes two parameters.
  • regex/substring : Regular expression or a substring.
  • replacetext : What the word will be replaced with. This needs to be a string.
Example
var mystr="Hello user !"; 
mystr.replace("user",'Sachin'); 
Its output is:
Hello Sachin !
To perform case insensitive search we use '/i' in the regex
For example
var mystr="Hello user !"; 
mystr.replace(/user/i,'Sachin'); 
var mystr="Hello User !"; 
mystr.replace(/user/i,'Sachin'); 
In both case output would be same.
Now for global replace '/g' is used.
var mystr="Hello user ! Thanks for logging in user."; 
mystr.replace(/user/g,'Sachin'); 
Its output is:
Hello Sachin ! Thanks for logging in Sachin.
To obtain global, case insensitive search we need to use 'g' and 'i' together.
var mystr="Hello user ! Thanks for logging in User."; 
mystr.replace(/user/gi,'Sachin'); 
Its output is:
Hello Sachin ! Thanks for logging in Sachin.

How To Fade Out And Remove A Div After Certain Time in jQuery

Tuesday, August 23, 2011

Here’s a handy bit of code that I use often. Sometime you need to notify user about something and after some time it is needed to be removed. At such time, jQuery’s this snippet is sure shot work. Time after you have to remove is passed in milliseconds. For 1 second, you have to pass 1000. After that time, first fading out occurs followed by removing that from DOM.
jQuery(document).ready(function($){
 setTimeout(function() {
   $('#div-to-remove').fadeOut('slow',function(){
    $('#div-to-remove').remove(); 
   }); 
 }, 5000); 
});  
In this example, the div with id ‘div-to-remove’, will be faded out and removed in 5 seconds.

How to restore Grub boot loader after installing Windows

Monday, August 22, 2011

If you run a dual-boot system with Linux and Windows, this case generally occurs. Window crashes and you have to reinstall Windows but it wipes out the MBR. Now you don’t see the linux bootloader anymore, so
you can’t boot into Ubuntu or whatever flavor of linux you prefer. I am using Ubuntu so I am here talking about Ubuntu.
So, this will help you to restore grub and get boot loader menu of Linux.
First boot your machine with Live Ubuntu CD. This can be the live installer cd or the older live session Ubuntu cds.
When you get to the desktop open a terminal and enter.
sudo grub
This will get you a “grub>” prompt (i.e. the grub shell). At grub> enter these commands
find /boot/grub/stage1
this will return a location. If you have more than one, select the installation that you want to provide the grub files.
Next, THIS IS IMPORTANT, whatever was returned for the find command use
it in the next line (you are still at grub>. when you enter the next 3
commands)
root (hd?,?)
Again use the value from the find command i.e. if find returned (hd0,1) then you would enter root (hd0,1) Next enter the command to install grub to the mbr
setup (hd0)
Finally exit the grub shell
quit
That is it. Grub will be installed to the mbr.
When you reboot, you will have the grub menu at startup.
Cheers.

How to create custom selector in jQuery

We know jQuery has powerful collection on selectors. Even more jQuery allows us to extend selectors as per our requirement.

In addition to the class and id selectors, there are many selection expressions that use the colon syntax like (:odd, :even, :first, :input, etc.). If one of the existing selectors doesn’t fit your needs, jQuery provides you the flexibility to create your own.
jQuery.extend(jQuery.expr[':'], {

		emptyValue: function(obj){

			return $(obj).val() == ''
		}
	});
In this example, we are going to create a selector nonEmpty which selects the fields whose value is not empty. The object obj is passed in the function. The function can be as simple as one line or complex. Here, we have checked the value and returned its result.
Returned value must be boolean.
Now our new selector can be used as following
$('#formid input:emptyValue').css('border','1px red solid');
Using this statement, all input element in ‘#form’ form with empty value will be applied with given CSS.

How to send mail with attachments using PHPMailer

PHP has default mail() function for sending mail. We can easily send mail using this function passing few parameters. But there is one nice class named ‘PHPMailer’ extending that function with lots of attractive and useful features. This PHPMailer, PHP email transport class features file attachments, SMTP servers, CCs, BCCs, HTML messages, word wrap, and more. Sends email via sendmail, PHP mail(), QMail, or with SMTP.
Here is an simple example to use PHPMailer.
$objMail = new PHPMailer;
$objMail->IsHTML(true);
$objMail->From='sender@gmail.com';
$objMail->FromName='Sender Name';
$objMail->AddEmbeddedImage("logo.jpg", 1, 'logo.jpg');
$objMail->Subject='Mail sent using PHPMailer';
$objMail->AddAddress('receiver@gmail.com', 'Receiver Name');
$objMail->AddAttachment('attachment.docx');
$objMail->Body='This is mail body';
$objMail->Send();
You can find detail documentation here

 
back to top