Showing posts with label jQuery Plugin. Show all posts
Showing posts with label jQuery Plugin. Show all posts

How to Add Select All Options to jQuery Select2 Plug-in

On 4/09/2018 Be the first to comment!

Hi, in this post let's see how to add select all options to jQuery Select2 plugin. Select2 is an excellent alternative to the standard HTML selection box that supports all its functions and provides greater flexibility. The plug-in is easy to setup and use. It supports multiple selection options where the selected elements will be added as pills to the top text box. You can also tag, search and load remote data-sets to select2 control.

Below we will see how to use select2 in your web projects, and select all options at once by ticking a check box using jquery.

jquery select2 select all options on click

How to Use Select2 jQuery Plug-in?

To implement Select2 plug-in in your projects, create a regular drop-down box with html markup as usual.

HTML:

<select id="states" style="width:300px">
    <option>Alaska</option>
    <option>Arizona</option>
    <option>California</option>
    <option>Florida</option>
    <option>Hawaii</option>
    <option>illinois</option>
    <option>Michigan</option>
    <option>North Dacota</option>
    <option>Ohio</option>
    <option>Washington</option>
</select>

This would produce a select box like this,

standard html select box example

Now load the library files for jquery and select2 on the html page. Do it only once on a page.

CSS:

<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2-rc.1/css/select2.min.css" rel="stylesheet" />

JS:

<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2-rc.1/js/select2.min.js" type="text/javascript"></script>

Finally bind the select2() method to the dropdown in this way,

$(document).ready(function() {
    $('#states').select2();
});

It will initialize the select2 control and convert the plain dropdown to this,

select2 single select example

Please note that you must wrap your code within the $(document).ready() block. This will ensure that the DOM is ready before initializing the select2 control.

Select2 Multiple Select Box:

Select2 also supports multiple selection option. All you have to do is to declare the multiple attribute to the input. This will add the selected options as pills to the text box at the top of the control.

Example:

<select id="states" multiple style="width:300px">
    <option>Alaska</option>
    <option>Arizona</option>
    <option>California</option>
    <option>Florida</option>
    <option>Hawaii</option>
    <option>illinois</option>
    <option>Michigan</option>
    <option>North Dacota</option>
    <option>Ohio</option>
    <option>Washington</option>
</select>

<script type="text/javascript">
$(document).ready(function() {
    $('#states').select2();
});
</script>

The above example will produce a dropdown box like this,

select2 multi select example

Add Select All Option to jQuery Select2:

Select2 also supports selecting all options at once from the list. Here we'll see how to select all the options when the user ticks the 'Select All' checkbox.

First create the markup for the multi-value select box and a check box for selecting all option.

<select id="states" multiple style="width:300px">
    <option>Alaska</option>
    <option>Arizona</option>
    <option>California</option>
    <option>Florida</option>
    <option>Hawaii</option>
    <option>illinois</option>
    <option>Michigan</option>
    <option>North Dacota</option>
    <option>Ohio</option>
    <option>Washington</option>
</select>

<input id="chkall" type="checkbox" >Select All

Now add this java script to the page.

<script type="text/javascript">
$(document).ready(function() {
    $('#states').select2();
    
    $("#chkall").click(function(){
        if($("#chkall").is(':checked')){
            $("#states > option").prop("selected", "selected");
            $("#states").trigger("change");
        } else {
            $("#states > option").removeAttr("selected");
            $("#states").trigger("change");
        }
    });
});
</script>

The above script will be executed by onclick() event of the check box. If checked, the script will set all the options of the select control as selected.

If you think this will alone do the job, you're wrong. This will simply keep all items in the dropdown selected, but will not add the selected items to the top of the control. For that we have to explicitly trigger the 'change' event.

select2 select all options example

Read other tutorials of select2,

That explains about jquery select2 and selecting all the options at once on click of the checkbox. The plugin offers so many customizations and adds flexibility to the standard html select box. I hope you like this tutorial. Meet you in another interesting post. Good day!

How to Add Images to Dropdown List using jQuery

On 3/30/2018 Be the first to comment!

Hi! In this post, let's see how to add images to dropdown list using jquery. I had a form with a drop-down element for the list of countries and wanted to insert the corresponding country flag before each country name. But HTML does not support the addition of elements to select box. Then I found some CSS hack but this method is not compatible with all browsers. Finally, I decided to go with java script and found a fairly neat solution.

Actually, it is a jquery plugin called 'select2'. It includes the autocomplete feature to dropdown list, but also allows you to add icons to those select options. Below, I'll show you how to use the select2 add-on to insert country flags before the country names in a drop-down list.

jquery add images to dropdown list

jQuery - Adding Images to the Dropdown List:

STEP-1) First load the 'jQuery' and 'Select2' libraries on the Web page. You need to add both 'css' and 'js' files of the plugin.

<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2-rc.1/css/select2.min.css" rel="stylesheet" />

<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2-rc.1/js/select2.min.js" type="text/javascript"></script>

STEP-2) Next, load the library for country flag icons. This will help us to display images of flags of all countries.

<link href="https://cdnjs.cloudflare.com/ajax/libs/flag-icon-css/0.8.2/css/flag-icon.min.css" rel="stylesheet" />

STEP-3) Now create an empty drop down element to add the country names and flags.

<select id="countries">
    <option></option>
</select>

STEP-4) Finally the JavaScript. This is the main part of the task. Here we have to create a JS array that contains all the country names and their IDs and pass it to the drop-down element that we created in the previous step.

<script type="text/javascript">
$(document).ready(function() {
    var options = [
        { id: 'AF', text: 'Afghanistan'},{ id: 'AX', text: 'Aland Islands'},{ id: 'AL', text: 'Albania'},{ id: 'DZ', text: 'Algeria'},{ id: 'AS', text: 'American Samoa'},
        { id: 'AD', text: 'Andorra'},{ id: 'AO', text: 'Angola'},
        { id: 'AI', text: 'Anguilla'},{ id: 'AQ', text: 'Antarctica'},{ id: 'AG', text: 'Antigua And Barbuda'},
        { id: 'AR', text: 'Argentina'},{ id: 'AM', text: 'Armenia'},{ id: 'AW', text: 'Aruba'},
        { id: 'AU', text: 'Australia'},{ id: 'AT', text: 'Austria'},{ id: 'AZ', text: 'Azerbaijan'},{ id: 'BS', text: 'Bahamas'},{ id: 'BH', text: 'Bahrain'},{ id: 'BD', text: 'Bangladesh'},{ id: 'BB', text: 'Barbados'},{ id: 'BY', text: 'Belarus'},{ id: 'BE', text: 'Belgium'},
        { id: 'BZ', text: 'Belize'},{ id: 'BJ', text: 'Benin'},
        { id: 'BM', text: 'Bermuda'},{ id: 'BT', text: 'Bhutan'},
        { id: 'BO', text: 'Bolivia'},{ id: 'BA', text: 'Bosnia And Herzegovina'},{ id: 'BW', text: 'Botswana'},    { id: 'BV', text: 'Bouvet Island'},{ id: 'BR', text: 'Brazil'},
        { id: 'IO', text: 'British Indian Ocean Territory'},{ id: 'BN', text: 'Brunei Darussalam'},{ id: 'BG', text: 'Bulgaria'},{ id: 'BF', text: 'Burkina Faso'},{ id: 'BI', text: 'Burundi'},{ id: 'KH', text: 'Cambodia'},{ id: 'CM', text: 'Cameroon'},{ id: 'CA', text: 'Canada'},
        { id: 'CV', text: 'Cape Verde'},{ id: 'KY', text: 'Cayman Islands'},{ id: 'CF', text: 'Central African Republic'},{ id: 'TD', text: 'Chad'},{ id: 'CL', text: 'Chile'},{ id: 'CN', text: 'China'},{ id: 'CX', text: 'Christmas Island'},{ id: 'CC', text: 'Cocos (Keeling) Islands'},{ id: 'CO', text: 'Colombia'},{ id: 'KM', text: 'Comoros'},{ id: 'CG', text: 'Congo'},{ id: 'CD', text: 'Congo, Democratic Republic Of'},{ id: 'CK', text: 'Cook Islands'},{ id: 'CR', text: 'Costa Rica'},{ id: 'CI', text: 'Cote D\'Ivoire'},{ id: 'HR', text: 'Croatia'},
        { id: 'CU', text: 'Cuba'},{ id: 'CY', text: 'Cyprus'},
        { id: 'CZ', text: 'Czech Republic'},{ id: 'DK', text: 'Denmark'},{ id: 'DJ', text: 'Djibouti'},{ id: 'DM', text: 'Dominica'},{ id: 'DO', text: 'Dominican Republic'},
        { id: 'EC', text: 'Ecuador'},{ id: 'EG', text: 'Egypt'},
        { id: 'SV', text: 'El Salvador'},{ id: 'GQ', text: 'Equatorial Guinea'},{ id: 'ER', text: 'Eritrea'},
        { id: 'EE', text: 'Estonia'},{ id: 'ET', text: 'Ethiopia'},{ id: 'FK', text: 'Falkland Islands (Malvinas)'},
        { id: 'FO', text: 'Faroe Islands'},{ id: 'FJ', text: 'Fiji'},{ id: 'FI', text: 'Finland'},{ id: 'FR', text: 'France'},{ id: 'GF', text: 'French Guiana'},{ id: 'PF', text: 'French Polynesia'},{ id: 'TF', text: 'French Southern Territories'},{ id: 'GA', text: 'Gabon'},{ id: 'GM', text: 'Gambia'},{ id: 'GE', text: 'Georgia'},{ id: 'DE', text: 'Germany'},{ id: 'GH', text: 'Ghana'},{ id: 'GI', text: 'Gibraltar'},{ id: 'GR', text: 'Greece'},
        { id: 'GL', text: 'Greenland'},{ id: 'GD', text: 'Grenada'},{ id: 'GP', text: 'Guadeloupe'},{ id: 'GU', text: 'Guam'},{ id: 'GT', text: 'Guatemala'},{ id: 'GG', text: 'Guernsey'},{ id: 'GN', text: 'Guinea'},{ id: 'GW', text: 'Guinea-Bissau'},{ id: 'GY', text: 'Guyana'},
        { id: 'HT', text: 'Haiti'},{ id: 'HM', text: 'Heard Island & Mcdonald Islands'},{ id: 'VA', text: 'Holy See (Vatican City State)'},{ id: 'HN', text: 'Honduras'},
        { id: 'HK', text: 'Hong Kong'},{ id: 'HU', text: 'Hungary'},{ id: 'IS', text: 'Iceland'},
        { id: 'IN', text: 'India'},{ id: 'ID', text: 'Indonesia'},
        { id: 'IR', text: 'Iran, Islamic Republic Of'},{ id: 'IQ', text: 'Iraq'},{ id: 'IE', text: 'Ireland'},{ id: 'IM', text: 'Isle Of Man'},{ id: 'IL', text: 'Israel'},
        { id: 'IT', text: 'Italy'},{ id: 'JM', text: 'Jamaica'},
        { id: 'JP', text: 'Japan'},{ id: 'JE', text: 'Jersey'},
        { id: 'JO', text: 'Jordan'},{ id: 'KZ', text: 'Kazakhstan'},{ id: 'KE', text: 'Kenya'},{ id: 'KI', text: 'Kiribati'},{ id: 'KR', text: 'Korea'},{ id: 'KW', text: 'Kuwait'},{ id: 'KG', text: 'Kyrgyzstan'},{ id: 'LA', text: 'Lao People\'s Democratic Republic'},{ id: 'LV', text: 'Latvia'},{ id: 'LB', text: 'Lebanon'},{ id: 'LS', text: 'Lesotho'},{ id: 'LR', text: 'Liberia'},{ id: 'LY', text: 'Libyan Arab Jamahiriya'},{ id: 'LI', text: 'Liechtenstein'},{ id: 'LT', text: 'Lithuania'},{ id: 'LU', text: 'Luxembourg'},{ id: 'MO', text: 'Macao'},
        { id: 'MK', text: 'Macedonia'},{ id: 'MG', text: 'Madagascar'},{ id: 'MW', text: 'Malawi'},{ id: 'MY', text: 'Malaysia'},{ id: 'MV', text: 'Maldives'},
        { id: 'ML', text: 'Mali'},{ id: 'MT', text: 'Malta'},
        { id: 'MH', text: 'Marshall Islands'},{ id: 'MQ', text: 'Martinique'},{ id: 'MR', text: 'Mauritania'},{ id: 'MU', text: 'Mauritius'},{ id: 'YT', text: 'Mayotte'},
        { id: 'MX', text: 'Mexico'},{ id: 'FM', text: 'Micronesia, Federated States Of'},{ id: 'MD', text: 'Moldova'},{ id: 'MC', text: 'Monaco'},{ id: 'MN', text: 'Mongolia'},{ id: 'ME', text: 'Montenegro'},{ id: 'MS', text: 'Montserrat'},{ id: 'MA', text: 'Morocco'},{ id: 'MZ', text: 'Mozambique'},{ id: 'MM', text: 'Myanmar'},
        { id: 'NA', text: 'Namibia'},{ id: 'NR', text: 'Nauru'},
        { id: 'NP', text: 'Nepal'},{ id: 'NL', text: 'Netherlands'},{ id: 'AN', text: 'Netherlands Antilles'},
        { id: 'NC', text: 'New Caledonia'},{ id: 'NZ', text: 'New Zealand'},{ id: 'NI', text: 'Nicaragua'},{ id: 'NE', text: 'Niger'},{ id: 'NG', text: 'Nigeria'},{ id: 'NU', text: 'Niue'},{ id: 'NF', text: 'Norfolk Island'},{ id: 'MP', text: 'Northern Mariana Islands'},{ id: 'NO', text: 'Norway'},{ id: 'OM', text: 'Oman'},{ id: 'PK', text: 'Pakistan'},{ id: 'PW', text: 'Palau'},{ id: 'PS', text: 'Palestinian Territory, Occupied'},{ id: 'PA', text: 'Panama'},{ id: 'PG', text: 'Papua New Guinea'},{ id: 'PY', text: 'Paraguay'},{ id: 'PE', text: 'Peru'},
        { id: 'PH', text: 'Philippines'},{ id: 'PN', text: 'Pitcairn'},{ id: 'PL', text: 'Poland'},{ id: 'PT', text: 'Portugal'},{ id: 'PR', text: 'Puerto Rico'},{ id: 'QA', text: 'Qatar'},{ id: 'RE', text: 'Reunion'},
        { id: 'RO', text: 'Romania'},{ id: 'RU', text: 'Russian Federation'},{ id: 'RW', text: 'Rwanda'},{ id: 'BL', text: 'Saint Barthelemy'},{ id: 'SH', text: 'Saint Helena'},
        { id: 'KN', text: 'Saint Kitts And Nevis'},{ id: 'LC', text: 'Saint Lucia'},{ id: 'MF', text: 'Saint Martin'},
        { id: 'PM', text: 'Saint Pierre And Miquelon'},{ id: 'VC', text: 'Saint Vincent And Grenadines'},{ id: 'WS', text: 'Samoa'},{ id: 'SM', text: 'San Marino'},{ id: 'ST', text: 'Sao Tome And Principe'},{ id: 'SA', text: 'Saudi Arabia'},{ id: 'SN', text: 'Senegal'},{ id: 'RS', text: 'Serbia'},{ id: 'SC', text: 'Seychelles'},{ id: 'SL', text: 'Sierra Leone'},{ id: 'SG', text: 'Singapore'},{ id: 'SK', text: 'Slovakia'},{ id: 'SI', text: 'Slovenia'},
        { id: 'SB', text: 'Solomon Islands'},{ id: 'SO', text: 'Somalia'},{ id: 'ZA', text: 'South Africa'},{ id: 'GS', text: 'South Georgia And Sandwich Isl.'},{ id: 'ES', text: 'Spain'},{ id: 'LK', text: 'Sri Lanka'},
        { id: 'SD', text: 'Sudan'},{ id: 'SR', text: 'Suriname'},
        { id: 'SJ', text: 'Svalbard And Jan Mayen'},{ id: 'SZ', text: 'Swaziland'},{ id: 'SE', text: 'Sweden'},{ id: 'CH', text: 'Switzerland'},{ id: 'SY', text: 'Syrian Arab Republic'},{ id: 'TW', text: 'Taiwan'},{ id: 'TJ', text: 'Tajikistan'},{ id: 'TZ', text: 'Tanzania'},
        { id: 'TH', text: 'Thailand'},{ id: 'TL', text: 'Timor-Leste'},{ id: 'TG', text: 'Togo'},{ id: 'TK', text: 'Tokelau'},{ id: 'TO', text: 'Tonga'},{ id: 'TT', text: 'Trinidad And Tobago'},{ id: 'TN', text: 'Tunisia'},
        { id: 'TR', text: 'Turkey'},{ id: 'TM', text: 'Turkmenistan'},{ id: 'TC', text: 'Turks And Caicos Islands'},{ id: 'TV', text: 'Tuvalu'},{ id: 'UG', text: 'Uganda'},{ id: 'UA', text: 'Ukraine'},{ id: 'AE', text: 'United Arab Emirates'},{ id: 'GB', text: 'United Kingdom'},{ id: 'US', text: 'United States'},{ id: 'UM', text: 'United States Outlying Islands'},{ id: 'UY', text: 'Uruguay'},{ id: 'UZ', text: 'Uzbekistan'},{ id: 'VU', text: 'Vanuatu'},{ id: 'VE', text: 'Venezuela'},{ id: 'VN', text: 'Viet Nam'},{ id: 'VG', text: 'Virgin Islands, British'},{ id: 'VI', text: 'Virgin Islands, U.S.'},{ id: 'WF', text: 'Wallis And Futuna'},{ id: 'EH', text: 'Western Sahara'},{ id: 'YE', text: 'Yemen'},
        { id: 'ZM', text: 'Zambia'},{ id: 'ZW', text: 'Zimbabwe'}
    ];
    $('#countries').select2({
        placeholder: '-Select Country-',
        templateResult: formatCountry,
        data: options
    });
    
    function formatCountry(country){
        if (!country.id) {
            return country.text;
        }
        var $country = $(
            '<span class="flag-icon flag-icon-'+ country.id.toLowerCase() +' flag-icon-squared"></span>' + '<span style="margin-left:10px;">'+ country.text+'</span>'
        );
        return $country;
    };
});
</script>

In the above script, the select2() method will simply replace the plain dropdown with a more customizable one. We also have to set the formatting function to the templateResult option. This will execute the function for each option in the drop down and will add a country flag image to it.

Run the script and you will see a nice dropdown that shows the country names with their flags. It also includes an amazing search box which will autosuggest the names of countries when you start typing.

insert country flag images before country names select2
Read Also:

Likewise, you can add images to the select box using the jquery select2 plugin. It's a nifty add-on that gives you more control over the element which you never get with HTML. I hope this tutorial is useful for you. Please share it on social media if you like it.

How to Create Treeview with Bootstrap and jQuery

On 2/12/2018 Be the first to comment!

Hi! Today let's see about creating treeview using bootstrap and jquery. A Treeview is a tree like representation of elements in a hierarchical structure. It offers a quick and easy navigation through websites. Although there are several jquery plugins available for tree view that simplify the task, I wanted something that works well with bootstrap.

And I found out a good library called 'Bootstrap Treeview'. It leverages the best of bootstrap framework and helps you display hierarchical tree structures using the JSON data set. You can do much more than a simple tree, like fetch data from the database and render a dynamic tree, make it collapsible, add icons, checkboxes and filters etc.

how to create treeview in bootstrap

Building Treeview with Bootstrap:

Now let's see how to add treeview in bootstrap. To build the menu, we need three different libraries,

  1. Bootstrap CSS
  2. jQuery
  3. Bootstrap Treeview

These libraries are available in the cdn, so you can load them directly on your projects without downloading. Here is the procedure.

Step-1) Load Stylesheets

First load the required style sheets into your html file. You need to link both 'bootstrap' and 'bootstrap treeview' css files.

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-treeview/1.2.0/bootstrap-treeview.min.css" rel="stylesheet" type="text/css" />

Step-2) Load JavaScript Libraries

Next you have to load the java script files. Be sure to load jquery before tree view to avoid dependency issues.

<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-treeview/1.2.0/bootstrap-treeview.min.js" type="text/javascript"></script>

Step-3) Create Placeholder for Tree View

Next add an html container to work as a placeholder for the tree view. Just a div block would do.

<div id="myTree"></div>

Step-4) Define JSON Data Structure

Now define the JSON structure required to hold the hierarchical data that will be displayed on the tree view menu.

var treeData = [
    {
        text: "Parent-Item-1",
        nodes: [
            {
                text: "Child-Item-1",
                nodes: [
                    {
                        text: "Grandchild-Item-1"
                    },
                    {
                        text: "Grandchild-Item-2"
                    }
                ]
            },
            {
                text: "Child-Item-2"
            }
        ]
    },
    {
        text: "Parent-Item-2"
    },
    {
        text: "Parent-Item-3"
    },
    {
        text: "Parent-Item-4"
    },
    {
        text: "Parent-Item-5"
    }
];

Step-5) Render the Treeview

Finally, display the tree structure in the placeholder element we have created in Step-3. For that, bind the treeview() method to the 'div' container and pass the json data to it.

$('#myTree').treeview({
    data: treeData
});

Above script will produce a tree view similar to this,

bootstrap treeview example

Read: Create Dynamic Treeview using PHP, MySQL and AJAX

Complete Script: index.html

<!DOCTYPE html>
<html>
<head>
    <title>Bootstrap Treeview Example</title>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
    <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-treeview/1.2.0/bootstrap-treeview.min.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <div class="col-sm-4">
        <div id="myTree"></div>
    </div>
    <script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-treeview/1.2.0/bootstrap-treeview.min.js" type="text/javascript"></script>
    <script type="text/javascript">
    $(document).ready(function(){
        var treeData = [
            {
                text: "Parent-Item-1",
                nodes: [
                    {
                        text: "Child-Item-1",
                        nodes: [
                            {
                                text: "Grandchild-Item-1"
                            },
                            {
                                text: "Grandchild-Item-2"
                            }
                        ]
                    },
                    {
                        text: "Child-Item-2"
                    }
                ]
            },
            {
                text: "Parent-Item-2"
            },
            {
                text: "Parent-Item-3"
            },
            {
                text: "Parent-Item-4"
            },
            {
                text: "Parent-Item-5"
            }
        ];
        $('#myTree').treeview({
            data: treeData
        });
    });
    </script>
</body>
</html>

In our example we have built a basic tree. But the plug-in offers several options to customize the appearance and behavior of the menu. Like changing colors, adding icons, badges and hyperlinks to the node items. Check here to know more about customizing options.

Read Also:

It's a hassle-free way to build a hierarchical tree-view using the bootstrap treeview plug-in. It works well with Apps that use bootstrap. I hope this post is useful for you. Please don't forget to share it on social networks if you like it.

CodeIgniter Autocomplete Search from Database using AJAX Example

On 2/09/2018 3 Comments so far

Hi! In this post, let's see how to autocomplete search from database using codeigniter and ajax. We are going to pull in live search thing something similar to Google search. As soon as you start typing in the textbox, the related suggestions will appear from the database. To implement this auto complete feature we need a jquery plugin called 'Select2'.

Select2 is an excellent plug-in that supercharges the regular select box with search functionality. It's really inappropriate to make the end user to skim through hundreds of options to pick just one. With Select2 the entire process is a breeze. It adds up a search filter to the dropdown (select box), thus populating results on fly with the help of ajax.

codeigniter autocomplete search from database ajax

AJAX Autocomplete Search from Database in CodeIgniter:

To implement the live autocomplete search in codeigniter, we need two JavaScript libraries, 1. jquery.js and 2. select2.js. Either download them or use from the cdn library just like I do in this demo.

Just follow the below steps and you'll be good.

Step-1) Create Database

For database, I'm going to use MySQL here. Create a dummy database, a table and some records to use in the example. Below is a sql file. Run the queries on mysql and it will take care of database creation.

CREATE `db_demo`;
USE `db_demo`;
CREATE TABLE IF NOT EXISTS `tbl_language` (
  `id` int(9) NOT NULL AUTO_INCREMENT,
  `lname` varchar(50) NOT NULL,
  `lcode` varchar(2) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=6;

INSERT INTO `tbl_language` (`id`, `lname`, `lcode`) VALUES
(1, 'English', 'en'),
(2, 'Afrikaans', 'af'),
(3, 'Greek', 'el'),
(4, 'Finnish', 'fi'),
(5, 'Spanish', 'es');

Step-2) Create Model

We need a codeigniter model to handle the database transactions. So create a model file inside 'application' > 'models' folder. It contains the function getLanguage() to fetch language names from the database that match the search term entered by the user.

SearchModel.php

<?php
class SearchModel extends CI_Model
{
    function __construct()
    {
        parent::__construct();
    }
    
    function getLanguage($str)
    {
        $this->db->select('id, lname as text');
        $this->db->like('lname', $str);
        $query = $this->db->get('tbl_language');
        return $query->result();
    }
}
?>

Step-3) Create Controller

Next create a controller file inside 'application' > 'controllers' folder. It contains two functions,

  1. index() - this is the default method that just loads the view file.
  2. search() - This function will be triggered during the ajax call. It receives the incoming search term ('q'), communicate with the model and get the results matching the search term, encode them to json and pass it back to the browser.

SearchController.php

<?php
class SearchController extends CI_Controller {
    function __construct()
    {
        parent::__construct();
        $this->load->helper('url');
        $this->load->database();
    }

    function index()
    {
        $this->load->view('SearchView');
    }
    
    function search()
    {
        $q = $this->input->get('q');
        $this->load->model('SearchModel');
        echo json_encode($this->SearchModel->getLanguage($q));
    }
}
?>

Step-4) Create View

This is the final step. Create a view file inside 'application' > 'views' folder. It contains all the front-end logic, including html markup, css and java script. Here is where we need to fire the ajax call. Just load the js libraries and bind the select2() method to the dropdown that requires auto complete feature.

SearchView.php

<!DOCTYPE html>
<html>
<head>
    <title>CodeIgniter Search from Database Example</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <h3>CodeIgniter Autocomplete Demo</h3>
    <select id="language" name="language" class="itemName form-control" style="width:300px" ></select>

    <script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
    
    <script type="text/javascript">
    $('#language').select2({
        placeholder: '-Select Language-',
        minimumInputLength: 1,
        ajax: {
            url: "<?php echo base_url();?>index.php/SearchController/search",
            dataType: 'json',
            delay: 250,
            processResults: function (data) {
                return {
                    results: data
                };
            },
            cache: true
        }
    });
    </script>
</body>
</html>

That's it! We have everything in place. It's time to test the search filter. Just run the controller and if everything is okay, you'll see a drop-down box. Start typing in the textbox and you will see the suggestions popping up below in a list.

ajax autocomplete search select2

With the plug-in, you can not only pull in the results from the database, but from other sources such as a remote REST API or just a local JS array.

Read Also:

That explains about implementing search from database in codeigniter and ajax. Most modern web apps uses autocomplete search and is a sure fire way to increase user experience. Every little detail counts! So make sure you implement it on your next project. I hope this tutorial is useful for you. Please share it on your social circle if you like it.

jQuery Animated Typing Effect using Typed.js Plugin

On 2/01/2018 Be the first to comment!

Hi! Today, we are going to see an interesting tutorial, which is to animate typing effect using jquery typed.js plugin. Not all animations require the skill of a graphics artist. You can pull in some really cool animations just with jquery plugins. jQuery has its share of animation plugins and 'Typed.js' is one among them. It is simple, lightweight and let you add typing effect to web pages. The text will be typed literally character by character thus giving you the impression it is being typed on a terminal.

Come, let's see how to implement this typing effect on websites.

jquery animated typing effect typed.js example

Adding Animated Typing Effect in jQuery:

Typed.js is a jquery library to simulate the terminal typing effect that allows you to print plain text or html as if you were typing on the screen.

How to Use it:

First create a container to print the string.

<div id="container"></div>

Then call the function typed() on the container element that we have created and provide the string(s) to be printed.

$("#container").typed({
    strings: ["String1", "String2", "..."]
});

You can add more than one string separated by commas. And can even style the screen cursor with css like this,

.typed-cursor {
    // add styles here
}

Below is the complete demo to animate dynamic typing.

<!DOCTYPE html>
<html>
<head>
    <title>Animated Typing Effect in jQuery</title>
    <style type="text/css">
    div {
        margin: 0 auto;
        width: 60%;
        min-height: 150px;
        text-align: center;
        background: #222;
    }
    
    #board, .typed-cursor {
        font-size: 40px;
        color: #FFF;
    }
    </style>
</head>
<body>
    <div>
        <span id="board"></span>
    </div>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js" type="text/javascript"></script>
    <script src="https://cdn.bootcss.com/typed.js/1.1.7/typed.min.js" type="text/javascript"></script>
    <script type="text/javascript">
    $(document).ready(function(){
        $("#board").typed({
            strings: ["This is the test.", "Have a Good Day!!!"],
            typeSpeed: 30
        });
    });
    </script>
</body>
</html>

Running this script would produce something like this,

typed js demo

You can pass several options to the method typed() and control the way it behaves. Above we have used only two options,

  1. strings - Defines the array of strings to be typed.
  2. typeSpeed - Defines the writing speed in milliseconds.

Apart from these two options, there are several others which you can refer in the official documentation of the plugin.

Read Also:

That explains about creating animated typing effect with jquery and typed.js. In the demo, I have loaded both 'js' libraries from CDN, but you can download and use them from your own server. I hope you find it useful. Please share the post with your friends if you like it.

How to Convert JSON Data to HTML Table using jQuery DataTables Plug-in

On 12/11/2017 17 Comments so far

Hi, this time I have come up with a jquery basics tutorial which discusses about how to convert json to html table. In simple terms we are going to use jquery to display data from a json file in neat table format with added pagination and search options to it. To make our life easier there is an excellent jquery plug-in called ‘DataTables’ which we will use for this task. DataTables is a flexible jquery tool which adds up advanced interaction controls to any HTML table. Using this we can easily add pagination, instant search or multi-column ordering to the html table. Moreover it supports all modern day data sources like DOM, JavaScript, Ajax and server-side processing.

Convert JSON Data to HTML Table using jQuery

As an example let’s take the below sample json file which contains an array of objects and display it in html table using datatables.

Don't Miss: How to Create Responsive Carousel Image Slider

Also Read: How to Create Image Lightbox Effect with jQuery

empdata.json

{
  "data": [
    {
      "name": "Garrett Winters",
      "designation": "Accountant",
      "salary": "$170,750",
      "joining_date": "2011/07/25",
      "office": "Tokyo",
      "extension": "8422"
    },
    {
      "name": "Brielle Williamson",
      "designation": "Integration Specialist",
      "salary": "$372,000",
      "joining_date": "2012/12/02",
      "office": "New York",
      "extension": "4804"
    },
    {
      "name": "Ashton Cox",
      "designation": "Junior Technical Author",
      "salary": "$86,000",
      "joining_date": "2009/01/12",
      "office": "San Francisco",
      "extension": "1562"
    },
    {
      "name": "Airi Satou",
      "designation": "Accountant",
      "salary": "$162,700",
      "joining_date": "2008/11/28",
      "office": "Tokyo",
      "extension": "5407"
    },
    {
      "name": "Caesar Vance",
      "designation": "Pre-Sales Support",
      "salary": "$106,450",
      "joining_date": "2011/12/12",
      "office": "New York",
      "extension": "8330"
    },
    {
      "name": "Shad Decker",
      "designation": "Regional Director",
      "salary": "$183,000",
      "joining_date": "2008/11/13",
      "office": "Edinburgh",
      "extension": "6373"
    },
    {
      "name": "Cedric Kelly",
      "designation": "Senior Javascript Developer",
      "salary": "$433,060",
      "joining_date": "2012/03/29",
      "office": "Edinburgh",
      "extension": "6224"
    },
    {
      "name": "Haley Kennedy",
      "designation": "Senior Marketing Designer",
      "salary": "$313,500",
      "joining_date": "2012/12/18",
      "office": "London",
      "extension": "3597"
    },
    {
      "name": "Colleen Hurst",
      "designation": "Javascript Developer",
      "salary": "$205,500",
      "joining_date": "2009/09/15",
      "office": "San Francisco",
      "extension": "2360"
    },
    {
      "name": "Dai Rios",
      "designation": "Personnel Lead",
      "salary": "$217,500",
      "joining_date": "2012/09/26",
      "office": "Edinburgh",
      "extension": "2290"
    },
    {
      "name": "Herrod Chandler",
      "designation": "Sales Assistant",
      "salary": "$137,500",
      "joining_date": "2012/08/06",
      "office": "San Francisco",
      "extension": "9608"
    },
    {
      "name": "Rhona Davidson",
      "designation": "Integration Specialist",
      "salary": "$327,900",
      "joining_date": "2010/10/14",
      "office": "Tokyo",
      "extension": "6200"
    },
    {
      "name": "Sonya Frost",
      "designation": "Software Engineer",
      "salary": "$103,600",
      "joining_date": "2008/12/13",
      "office": "Edinburgh",
      "extension": "1667"
    },
    {
      "name": "Jena Gaines",
      "designation": "Office Manager",
      "salary": "$90,560",
      "joining_date": "2008/12/19",
      "office": "London",
      "extension": "3814"
    },
    {
      "name": "Quinn Flynn",
      "designation": "Support Lead",
      "salary": "$342,000",
      "joining_date": "2013/03/03",
      "office": "Edinburgh",
      "extension": "9497"
    }
  ]
}

Now let's see about converting this json data to html table.

Step 1: First you need the datatables plug-in in place to start working. So download datatables plug-in here and extract its contents and move ‘media’ directory to your working folder.

Step 2: Having the required datatables files in place, now we have to link them to the html file. Create a file ‘index.html’ and link the datatables ‘css’ and ‘js’ files like this.

<html>
<head>
    <!-- link datatables css -->
    <link rel="stylesheet" type="text/css" href="/path/to/jquery.dataTables.css">
</head>
<body>

    ...

    <!-- load jquery -->
    <script type="text/javascript" src="/path/to/jquery-1.10.2.js"></script>
    <!-- load datatables js library -->
    <script type="text/javascript" src="/path/to/jquery.dataTables.js"></script>
</body>
</html>

Remember to include the jquery library before datatables ‘js’ file as the plug in is built over jquery.

Step 3: Now it's time to create a html table structure which we will map to our json data source later. We should determine what are the columns we want to appear on the table and create the table's header and footer with appropriate column names.

<table id="empTable" class="display" width="100%" cellspacing="0">
    <thead>
        <tr>
            <th>Name</th>
            <th>Designation</th>
            <th>Office</th>
            <th>Extension</th>
            <th>Joining Date</th>
            <th>Salary</th>
        </tr>
    </thead>

    <tfoot>
        <tr>
            <th>Name</th>
            <th>Designation</th>
            <th>Office</th>
            <th>Extension</th>
            <th>Joining Date</th>
            <th>Salary</th>
        </tr>
    </tfoot>
</table>

Using the css class ‘.display’ will create the table with alternative striped rows (zebra cross style).

Step 4: Finally we should populate the html table with the data from json source by mapping to the right table columns.

<script type="text/javascript">
$( document ).ready(function() {
    $('#empTable').dataTable({
        "ajax": "empdata.json",
        "columns": [
            {"data": "name"},
            {"data": "designation"},
            {"data": "office"},
            {"data": "extension"},
            {"data": "joining_date"},
            {"data": "salary"}
        ]
    });   
});
</script>

- The dataTable() method will initialize the datatables. Its behavior can be controlled by passing parameters for various options and we have used two options in the above code. (I planned to keep the code as simple as possible and used only the basic options required but you can try out more).

- The ajax option will load the data from the given ajax source. Here in our case it’s the path to the json file.

- The columns option will map the table columns to the data source keys.

Now run the index.html file and you can see a nicely designed html table with added enhancements like instant-search at the top and pagination links at the bottom. You can also sort the table columns like you prefer.

display-json-data-in-html-table-datatables-jquery-example
JSON Data Displayed in HTML Table using jQuery Datatables Plug-in

Complete Code for index.html

<!DOCTYPE html>
<html>
<head>
    <title>Display JSON File Data in Datatables | Example</title>
    <!-- link datatables css -->
    <link rel="stylesheet" type="text/css" href="/path/to/jquery.dataTables.css">
</head>
<body>
    <table id="empTable" class="display" width="100%" cellspacing="0">
        <thead>
            <tr>
                <th>Name</th>
                <th>Designation</th>
                <th>Office</th>
                <th>Extension</th>
                <th>Joining Date</th>
                <th>Salary</th>
            </tr>
        </thead>
        <tfoot>
            <tr>
                <th>Name</th>
                <th>Designation</th>
                <th>Office</th>
                <th>Extension</th>
                <th>Joining Date</th>
                <th>Salary</th>
            </tr>
        </tfoot>
    </table>
    
    <!-- load jquery -->
    <script type="text/javascript" src="/path/to/jquery-1.10.2.js"></script>
    <!-- load datatables js library -->
    <script type="text/javascript" src="/path/to/jquery.dataTables.js"></script>
    
    <script type="text/javascript">
    $(document).ready(function() {
        $('#empTable').dataTable({
            "ajax": "empdata.json",
            "columns": [
                {"data": "name"},
                {"data": "designation"},
                {"data": "office"},
                {"data": "extension"},
                {"data": "joining_date"},
                {"data": "salary"}
            ]
        });   
    });
    </script>
</body>
</html>

I hope this basic jquery tutorial gives you a good idea about converting json data to html table using datatables jquery plugin.

Read Also:

As said earlier it's a highly flexible tool and provides wide range of options to completely customize the looks and behavior of the html tables to meet your requirements. Don't hesitate to try out :-)

jQuery Password Strength Meter for Twitter Bootstrap Example

On 12/08/2017 1 Comment so far

Hi, I'm back with another useful and interesting tutorial that talks about implementing jQuery Password Strength Meter to Twitter Bootstrap Framework. Guiding users to choose complex passwords and let them know the strength of their selected passwords during user registration process (signup) is a good and necessary practice to include in websites. Having password strength checker not only improves overall site security but will also gain users trust. Here we'll see how to incorporate it on websites built over twitter bootstrap css framework.

jquery-password-strength-meter-twitter-bootstrap-example

Password Strength Meter for Twitter Bootstrap

In order to implement password strength meter to bootstrap, we need a jquery plug-in called 'Pwstrength' which attach a nicely animated progress bar to the password input field and show up a real-time password strength checker. This jquery plug-in heavily relies on bootstrap framework and it requires it for the plugin to work properly.

Implementing Password Strength Meter

To create a working example first let's download the jquery plug-in. Go to this Github repository and download the plugin. Extract the zip file and move the 'pwstrength.js' file to your working folder.

Now create a file named 'index.html' and load bootstrap, jquery and pwstrength plug-in files like this.

<html>
    <head>
    <meta charset="utf-8"> 
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jQuery Password Strength Meter Example</title>
    <link href="path/to/bootstrap.css" rel="stylesheet" type="text/css" />
</head>
<body>

    ...
    <script src="path/to/jquery-1.10.2.js" type="text/javascript"></script>
    <script src="path/to/bootstrap.js" type="text/javascript"></script>
    <script src="path/to/pwstrength.js" type="text/javascript"></script>
</body>
</html>

Next create a html form with password field and a container (<div> element) to hold the progress bar.

<div class="container">
<div class="row" id="pwd-container">
    <div class="col-md-6 col-md-offset-3">
        <div class="panel panel-default">
            <div class="panel-heading">
                <h4 class="text-center">jQuery Password Strength Meter Example</h4>
            </div>
            <div class="panel-body">
                <form role="form" method="post">
                    <div class="form-group">
                        <label for="password">Password</label>
                        <input class="form-control" id="password" name="password" placeholder="Enter Password" type="password" />
                    </div>

                    <div class="form-group">
                        <label>Password Strength</label>
                        <div class="progress_meter"></div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
</div>

Now having the form in place we have to attach password strength meter to the password field. To do it, add the below jquery script to 'index.html' file.

<script type="text/javascript">
    $(document).ready(function () {
    "use strict";
    var options = {};
    options.ui = {
        container: "#pwd-container",
        showVerdictsInsideProgressBar: true,
        viewports: {
            progress: ".progress_meter"
        }
    };
    $('#password').pwstrength(options);
});
</script>

The method pwstrength() will attach a progress meter to the password field with css selector #password. You can invoke multiple instances of strength checker in a same page. For that you can use $(':password').pwstrength(options); statement. This will attach the progress meter to all the password fields.

The option showVerdictsInsideProgressBar when set as TRUE will display the verdicts such as 'Weak', 'Normal', 'Medium', 'Strong', 'Very Strong' based upon the keyed-in password inside the progress bar.

Complete Code for index.html

<html>
    <head>
    <meta charset="utf-8"> 
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jQuery Password Strength Meter Example</title>
    <link href="path/to/bootstrap.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <div class="container">
    <div class="row" id="pwd-container">
        <div class="col-md-6 col-md-offset-3">
            <div class="panel panel-default">
                <div class="panel-heading">
                    <h4 class="text-center">jQuery Password Strength Meter Example</h4>
                </div>
                <div class="panel-body">
                    <form role="form" method="post">
                        <div class="form-group">
                            <label for="password">Password</label>
                            <input class="form-control" id="password" name="password" placeholder="Enter Password" type="password" />
                        </div>

                        <div class="form-group">
                            <label>Password Strength</label>
                            <div class="progress_meter"></div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
    </div>
    <script src="path/to/jquery-1.10.2.js" type="text/javascript"></script>
    <script src="path/to/bootstrap.js" type="text/javascript"></script>
    <script src="path/to/pwstrength.js" type="text/javascript"></script>
    <script type="text/javascript">
    $(document).ready(function () {
        "use strict";
        var options = {};
        options.ui = {
            container: "#pwd-container",
            showVerdictsInsideProgressBar: true,
            viewports: {
                progress: ".progress_meter"
            }
        };
        $('#password').pwstrength(options);
    });
    </script>
</body>
</html>

That's it. Now run 'index.html' file in browser and you can see a form like this.

jquery-password-strength-meter-twitter-bootstrap
Bootstrap Password Strength Meter Example

Just type in your password and the progress bar indicates its strength with different verdicts and colors. Check here for customizing the rule sets and options of the plug-in.

Read Also:

I hope now you have better understanding of implementing jquery password strength meter in twitter bootstrap.

Image Lightbox Effect with jQuery

On 11/30/2017 Be the first to comment!

LightBox is a popup window that is used to open up images, html contents & other multimedia stuffs. This effect can be produced with css and js but using addons will simplify the task. In this tutorial I will show you how to add such lightbox effect to images with a jQuery plugin, called FancyBox. FancyBox plugin lets you produce clean and elegant lightbox effect with smooth animations. Download the latest version of the plugin here, extract the contents and move the folder 'source' to your working folder.

Image-Lightbox-effect-jquery

Add Image LightBox Effect using jQuery

First we need to include the required js and css files. FancyBox plugin is built over the jQuery library so we should load the jquery file first for the plugin to work.

Recommended Read: How to add Photo Frame Effect to Images using pure CSS

<!-- include jQuery library -->
<script type="text/javascript" src="js/jquery-1.10.1.min.js"></script>
<!-- include fancyBox JS and CSS files -->
<script type="text/javascript" src="fancybox_assets/jquery.fancybox.js"></script>
<link rel="stylesheet" type="text/css" href="fancybox_assets/jquery.fancybox.css" media="screen" />

Next add image(s) with anchor link like this.

<a class="fancybox-elastic" title="Lorem ipsum dolor" href="images/1.jpg"><img src="images/1.jpg" alt="Butterfly1" /></a>
 
<a class="fancybox-fade" title="Lorem ipsum dolor" href="images/2.jpg"><img src="images/2.jpg" alt="Butterfly2" /></a>

<a class="fancybox-over" title="Lorem ipsum dolor" href="images/3.jpg"><img src="images/3.jpg" alt="Butterfly3" /></a>

<a class="fancybox-inside" title="Lorem ipsum dolor" href="images/4.jpg"><img src="images/4.jpg" alt="Butterfly4" /></a>

<a class="fancybox-outside" title="Lorem ipsum dolor" href="images/5.jpg"><img src="images/5.jpg" alt="Butterfly5" /></a>

Now time for some general CSS styles.

body {
    margin: 0 auto;
    padding: 20px;
}

img {
    width: 150px;
    height: 150px;
}

.fancybox-custom .fancybox-skin {
    box-shadow: 0 0 50px #222;
}

Next invoke the fancybox window with jQuery.

Recommended Read: 10 Amazing CSS Drop Cap Effects you can Copy Paste

$(document).ready(function() {
    $(".fancybox-elastic").fancybox({
        openEffect : 'elastic',
        openSpeed  : 150,
        closeEffect : 'elastic',
        closeSpeed  : 150,
        closeClick : true,

        helpers: {
            title : {
                type : 'inside',
            },
            overlay : null
        }
    });
    
    $(".fancybox-fade").fancybox({
        padding: 0,
        openEffect : 'fade',
        openSpeed  : 300,
        closeEffect : 'fade',
        closeSpeed  : 300,

        helpers: {
            title : {
                type : 'float',
            }
        }
    });
    
    $(".fancybox-over").fancybox({
        openEffect : 'none',
        closeEffect : 'none',
        closeClick : true,
        helpers: {
            title : {
                type : 'over',
            },
            overlay : null
        }
    });

    $(".fancybox-inside").fancybox({
        openEffect : 'elastic',
        openSpeed  : 'slow',
        closeEffect : 'elastic',
        closeSpeed  : 'slow',
        closeClick : true,
        helpers: {
            title : {
                type : 'inside',
                position: 'top'
            }
        }
    });

    $(".fancybox-outside").fancybox({
        openEffect : 'fade',
        openSpeed  : 'normal',
        closeEffect : 'fade',
        closeSpeed  : 'fast',
        helpers: {
            title : {
                type : 'outside',
                position: 'bottom'
            }
        }
    });
});

I have used css class selector to define the fancybox, but you can also use id's, but they should be used to a single element.

To create the image lightbox effect we've used some properties of fancybox plug-in. Let’s see them in detail one by one.

  1. The properties 'openEffect', 'closeEffect' are for animation effect and it can be any one of elastic, fade or none value.
  2. Properties 'openSpeed' & 'closeSpeed' defines the transition speed and should be of slow, normal, fast or ms(milli seconds).
  3. If 'closeClick' is set to true, fancyBox window will be closed when user clicks the content.

FancyBox Plugin Helpers

The plug-in comes with Helpers to extend the capabilities. 'overlay' and 'title' are the two built-in helpers and can be set with custom properties or disabled if not required.

The title type could be any one of float, inside, outside or over.

Download Code View Demo

Hope you have enjoyed this image lightbox effect tutorial. Kindly share it in your circle and help spread our word.

Best 7 jQuery File Upload Plugins (Drag and Drop, Progress Bar)

On 5/23/2017 Be the first to comment!

Hi! Here's some of the best jquery file upload plugins for your next project. Implementing file uploading is one big headache as you have to take care of things like security; handling multiple uploads, dealing with too large files etc. And then there's this user experience sort of things like drag and drop, progress bar and providing file preview. Overall you have to sort out so many things during uploading process. If you don't want to go through all these hassle then use any one of the readily available jquery file upload plug in.

Below we have handpicked some of the best file upload plugins in jquery to make your life easier. They come with so many customizing options and let you integrate beautiful file uploader to your websites quickly and serve rich user experience.

best jquery file upload plugins with progress bar

7 Best jQuery File Upload Plugins:

1. Uploadify

Read: Drag and Drop Multiple File Upload in jQuery & AJAX

Uploadify plug-in let you integrate multiple file upload functionality to your website easily. This file upload plugin offers extreme customization and available as both HTML5 and Flash versions for you to choose from. What we like most is the ability to upload multiple files without clustering the page with numerous browse buttons, real-time progress bar and drag-drop support with HTML5 version.

Key Features:

  • Multiple file upload without multiple browse buttons
  • Drag and drop files to upload queue
  • Real time progress bar to show uploading status
  • Highly Customizable to suit your need
  • Restrict uploads based on file size, type, quantity etc

Visit Website

2. Droply JS

Droply is a light-weight responsive jQuery based plug-in to setup single or multi-file upload feature to websites. As a developer your time is precious, so using droply.js will give you the leverage to add beautiful and professional file uploader to websites without going through the hassle of implementing everything from scratch. The highly configurable settings and ease-of-use makes it a remarkable file uploader plug in.

With Droply users can easily upload extremely large files of several giga-bytes with ease as it employs the latest chunk upload technique. And the best part is its minimal size without comprising rich features it offers. It is written in pure jquery so compatible with all platforms.

Key Features:

  • Responsive multi-file uploader
  • Drag and drop Files support
  • Delete files from upload queue
  • Employs smooth CSS3 effects
  • Progress indicator & file preview options
  • Compatible with Android and iOS

Visit Website

3. Plupload

Plupload is another great choice if you need a file uploader with ready to build User Interface. It is based on HTML5 APIs and offers limited customizations. But Flash and Silverlight fallbacks, numerous readily available themes and multi-lingual packs makes it worth trying. Plus it uploads files in chunks and let you bypass any server limitation on uploading bigger files.

Read: jQuery Drop Down List with Search Example

Key Features:

  • Multi-uploader using HTML5 APIs
  • Drag-and-Drop file support
  • Instant thumbnail preview
  • Shrink Images on Client-Side to save bandwidth
  • Upload in Chunks to support large files
  • Support for 30+ languages

Visit Website

4. FineUploader

FineUploader is a flexible library written in pure JavaScript but available as jquery plugin too. It includes all sorts of basic functionalities you require in a file uploader plugin like single/multiple file uploads, drag and drop files, real-time progress indicator and file preview options. What if you have uploaded a wrong file? Well! With fineuploader you get a nice option to delete uploaded files.

Besides the plug-in offers so many interesting features like pause & resume uploads, file partitioning, entire folder uploading, image scaling, uploading directly to cloud like Amazon S3 or Microsoft Blob Storage service etc.

Key Features:

  • Pause, Resume & Retry Uploads
  • Cancel uploads in the middle
  • Support for Cloud uploading
  • Delete already uploaded files
  • File Chunking / Partitioning
  • ES6 modules & CommonJS Support
  • Upload from mobile camera

Visit Website

5. jQuery File Upload

jQuery File Upload is another good jquery plugin for simplified file uploading and saving. It offers versatile range of options supporting multiple file upload, drag and drop feature, status bar indicator, file preview and much more. Plus you can cancel and resume upload at any time. It also supports uploading large file in chunks and let you edit and resize images after uploading.

jQuery File Upload Plug in is cross-domain compatible which is another good reason to go for. It works with all sorts of server platforms like PHP, Python, Java, Node.js, Ruby on Rails etc that supports standard HTML file uploads.

Key Features:

  • Multiple file uploads
  • Drag & Drop files
  • Progress bar Support
  • Cancel/Resume uploads
  • Image resizing via JS APIs
  • Preview images/audio/video
  • Highly configurable & extendable

Visit Website

6. DropzoneJS

Dropzone is an open source library that turns out any HTML element into a potential dropzone area. It employs AJAX technology and let user drag and drop files onto it for uploading. The library is extremely light-weight and written on pure java script. Includes so many nice features like multiple uploads, progress bar, image preview & resize, configure file limits, rename file during uploads etc.

Dropzone is compatible with browsers like Chrome, Firefox, IE, Safari, Opera but not work in older versions which doesn't support drag’n’drop. So make sure to check for browser compatibility.

Key Features:

  • Multiple files & synchronous uploads
  • Progress bar indicator
  • Support for big files
  • Drag-and-drop
  • Image Preview
  • Enabled Retina

Visit Website

7. Bootstrap File Input

If you need something to work with Bootstrap then this is for you. Bootstrap File Input Plugin works with Bootstrap 3.x and an enhanced version of standard HTML5 file element with multiple file selection, preview support for various types of files such as html, image, audio, video, flash and objects. Further you can simply drag and drop files for uploading, preview, add and delete uploaded files. It is based on AJAX and relies on Bootstrap CSS3 styles.

Key Features:

  • Multiple File uploads
  • Drag and drop
  • Multi-file preview
  • Multi language widgets
  • Image Resizing
  • Configurable layout & style

Visit Website

Also Read:

Simple AJAX Pagination in jQuery, PHP PDO & MySQL

On 1/02/2017 2 Comments so far

Hi! Happy New Year 2017!!!

This is my first post in the new year and let's see how to create simple ajax pagination in php pdo, mysql and jquery. Pagination script adds on for user experience by allowing users to skim through data across multiple pages instead of endless scrolling. But while implementing pagination in php certain things has to be taken care of.

For the matter, the process may get complicated with too many lines of code when not using external libraries or plugins. And refreshing the page every time user clicks on a page link is not going to look pleasant. You'll definitely need to be using AJAX.

So to simplify the process I'm going to use a jQuery plugin called Bootpag which is light-weight and handles ajax request at the background effortlessly. The plug-in rely on bootstrap framework.

Below I have shared a simple php pagination script. It fetch and display mysql record in a html table and split the records over multiple pages with pagination links at the bottom for navigation.

Read:

Create MySQL Database & Table:

Here are the sql commands to create required database and table. Run them in mysql interface to create db & table.

CREATE DATABASE IF NOT EXISTS `kms_demo`;

USE `kms_demo`;

CREATE TABLE IF NOT EXISTS `customers` (
  `id` int(8) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) NOT NULL,
  `email` varchar(60) NOT NULL,
  `city` varchar(50) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=14;

INSERT INTO `customers` (`id`, `name`, `email`, `city`) VALUES
(1, 'Jim Connor', 'jimconnor@yahoo.com', 'Las Vegas'),
(2, 'Taylor Fox', 'taylorfox@hotmail.com', 'San Francisco'),
(3, 'Daniel Greyson', 'danielgreyson@hotmail.com', 'New York'),
(4, 'Julia Brown', 'juliabrown@gmail.com', 'Los Angeles'),
(5, 'Rose Harris', 'roseharris@gmail.com', 'New York'),
(6, 'Lilly Whites', 'lillywhites@outlook.com', 'New York'),
(7, 'Jennifer Winters', 'jennie.winters001@gmail.com', 'Miami'),
(8, 'Michael Bruce', 'michaelbruce78@yahoo.com', 'Los Angeles'),
(9, 'John Alex', 'johnalex@example.com', 'Chicago'),
(10, 'Demi Milan', 'demimilan@gmail.com', 'Austin'),
(11, 'Austin Joseph', 'austin.joseph.boston@gmail.com', 'Boston'),
(12, 'Mark Higgins', 'mark.higgins21@yahoo.com', 'Houston'),
(13, 'Sean Kennedy', 'seankennedy.boss@outlook.com', 'Seattle');

Simple AJAX Pagination using jQuery & PHP PDO

First make sure you have all the below library files in place and then move on to coding part.

root
|__css
|    |___ bootstrap.min.css
|
|__js
    |___ bootstrap.min.js
    |___ jquery-1.10.2.js
    |___ jquery.bootpag.min.js

db_connect.php

This is the database configuration file. Here's where you define connection details to mysql and more importantly the number of records visible per page. Also I have used PDO library instead of mysqli to connect php to mysql database.

<?php
$hostname = "localhost";
$username = "username"; // change to yours
$password = "password"; // change to yours
$database = "kms_demo";
$row_limit = 5;

// connect to mysql
try {
    $pdo = new PDO("mysql:host=$hostname;dbname=$database", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $err) {
    die("Error! " . $err->getMessage());
}
?>

The variable $row_limit defines number of records to be displayed per page. Just change this limit according to your need.

index.php

It is the main file to show records from mysql db as html table along with pagination links at the bottom. The database records are split into several pages and displayed one page at a time. In order to generate pagination links we need to calculate the number of pages. You have to just divide the total number of records by rows per page.

<?php
include_once("db_connect.php");

$stmt = $pdo->prepare("SELECT COUNT(*) FROM customers");
$stmt->execute();
$rows = $stmt->fetch();

// get total no. of pages
$total_pages = ceil($rows[0]/$row_limit);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <title>AJAX Pagination using PHP & MySQL</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="css/bootstrap.min.css" rel="stylesheet" type="text/css" />
    <style type="text/css">
    .panel-footer {
        padding: 0;
        background: none;
    }
    </style>
</head>
<body>
<br/>
<div class="container">
    <div class="panel panel-default">
        <div class="panel-heading text-center"><h3>jQuery PHP Pagination Demo</h3></div>

        <table class="table table-bordered table-hover">
            <thead>
                <tr>
                    <th>#</th>
                    <th>Name</th>
                    <th>Email ID</th>
                    <th>Location</th>
                </tr>
            </thead>
            <tbody id="pg-results">
            </tbody>
        </table>
        <div class="panel-footer text-center">
            <div class="pagination"></div>
        </div>
    </div>
</div>
    
<script src="js/jquery-1.10.2.js" type="text/javascript"></script>
<script src="js/bootstrap.min.js" type="text/javascript"></script>
<script src="js/jquery.bootpag.min.js" type="text/javascript"></script>

<script type="text/javascript">
$(document).ready(function() {
    $("#pg-results").load("fetch_data.php");
    $(".pagination").bootpag({
        total: <?php echo $total_pages; ?>,
        page: 1,
        maxVisible: 5
    }).on("page", function(e, page_num){
        e.preventDefault();
        /*$("#results").prepend('<div class="loading-indication"><img src="ajax-loader.gif" /> Loading...</div>');*/
        $("#pg-results").load("fetch_data.php", {"page": page_num});
    });
});
</script>

</body>
</html>

Do you notice that we haven't used any ajax() function in our script? Here's where the bootpag plugin comes into play. It takes care of ajax call at the background. All you have to do is, use the plugin's load() method to load the page results and bootpag() method to display pagination links and the rest of the things will be taken care automatically.

fetch_data.php

This script will be executed during ajax request. It pulls of the records from the database by using LIMIT Query and returns only a small set of rows to be displayed on a particular page.

<?php
include_once("db_connect.php");

if (isset($_POST["page"])) {
    $page_no = filter_var($_POST["page"], FILTER_SANITIZE_NUMBER_INT, FILTER_FLAG_STRIP_HIGH);
    if(!is_numeric($page_no))
        die("Error fetching data! Invalid page number!!!");
} else {
    $page_no = 1;
}

// get record starting position
$start = (($page_no-1) * $row_limit);

$results = $pdo->prepare("SELECT * FROM customers ORDER BY id LIMIT $start, $row_limit");
$results->execute();

while($row = $results->fetch(PDO::FETCH_ASSOC)) {
    echo "<tr>" . 
    "<td>" . $row['id'] . "</td>" . 
    "<td>" . $row['name'] . "</td>" . 
    "<td>" . $row['email'] . "</td>" . 
    "<td>" . $row['city'] . "</td>" . 
    "</tr>";
}
?>

That's it! Now we have the complete set of coding for ajax driven pagination using php & mysql. Run index.php and you can see the records displayed on html table with pagination links.

ajax-pagination-in-php-mysql-jquery

Initially it will show you the results for the first page and you have to click on the page links to navigate to other pages.

simple-pagination-bootstrap-jquery-php-pdo
Also Read:

I hope you find this simple ajax pagination script with jquery, php pdo & mysql useful. The code is highly customizable and you have all the required things in place. If you have any queries then please let me know through comments.

How to Use Datepicker in Codeigniter using jQuery | Example

On 8/12/2016 Be the first to comment!

This tutorial will show you how to use datepicker in codeigniter forms using jquery. A date picker is an interactive control which makes it easy for the user to choose the date from a calendar rather typing it manually. Honestly who wants to type into web forms let alone date these days? Besides it's a great way to avoid typos and enhance user experience too.

There are so many ways by which you can add datepicker in codeigniter, but jquery ui datepicker so far is simple and rich in features. This datepicker calendar will be tied to form input and opened in a small overlay beneath the text box. Below we'll see how to use datepicker in codeigniter with jquery ui plug-in.

How to Add Datepicker in CodeIgniter using jQuery UI?

To use jquery datepicker in codeigniter form, first you'll need to download jQuery UI plugin and move the files to your codeigniter application. Make sure to place them along with your other assets like css, js for easier access.

Next you have to include the plug-in's css and js files to codeigniter view. Since the plugin is built over jquery you'll also need to include the library for the datepicker to work.

So include jquery ui style sheet inside <head></head> of your code igniter view.

<head>
    ...
    <!--link jquery ui css-->
    <link type="text/css" rel="stylesheet" href="<?php echo base_url('assets/jquery-ui-1.12.0/jquery-ui.css'); ?>" />
</head>

Next load jquery and jquery ui's js files just above the closing body tag (</body>).

<!--load jquery-->
<script src="<?php echo base_url('assets/js/jquery-1.10.2.js'); ?>"></script>
<!--load jquery ui js file-->
<script src="<?php echo base_url('assets/jquery-ui-1.12.0/jquery-ui.js'); ?>"></script>

Now create a text input to codeigniter form to which you can add datepicker control.

<label for="dob">Date of Birth</label>
<?php $attributes = 'id="dob" placeholder="Date of Birth"';
echo form_input('dob', set_value('dob'), $attributes); ?>

Here is the final step to add datepicker in codeigniter. Add this script just above the </body> tag.

<script type="text/javascript">
$(function() {
    $("#dob").datepicker();
});
</script>

The function datepicker() is used to invoke the month calendar - and the above script makes the datepicker calendar to popup as soon as the dob field got focus.

add-jquery-datepicker-in-codeigniter-example

You can also customize the way the datepicker control behaves using its options. For example its default date format is 'mm/dd/yy'. If you want to change it to the common date format used in databases then set dateFormat option inside datepicker() like this,

$("#dob").datepicker(
    {
        dateFormat: 'yy-mm-dd'
    }
);

This setting will be helpful in case you wish to insert the date input to database. It will save you the additional computing time required to change the date format and store it into db.

Read Also: How to Populate Dropdown from Database in CodeIgniter

Likewise you can easily use datepicker in codeigniter forms using jQuery ui plugin. I hope you find this little codeigniter tutorial useful. Meet you in another interesting post.

Create Drop Down List with Search using jQuery | Example

On 2/25/2016 Be the first to comment!

Hi! In this post let's see how to create drop down list with search using jQuery. With dropdown list you can easily control what user inputs, but what if the drop down combo contains long list of values to skim through. Say you have a drop down containing country names (which is huge), wouldn't it be nice to provide a search box to easily narrow down the choice? That's what we are going to do here. Create a searchable drop down list in jquery!

Contact Form

Name

Email *

Message *