Showing posts with label jquery. Show all posts
Showing posts with label jquery. Show all posts

Wednesday, 6 September 2017

jQuery multi column sorting with jQuery - Live Demo

jQuery multi column sorting with jQuery

tablesorter is a jQuery plugin used for turning a standard HTML table with THEAD and TBODY tags into a sortable table without page refreshes also no ajax call. tablesorter can successfully parse and sort many types of data including linked data in a cell. It has many useful features including:
  • Multi-column sorting
  • Parsers for sorting text, URIs, integers, currency, floats, IP addresses, dates (ISO, long and short formats), time. Add your own easily
  • Support secondary "hidden" sorting (e.g., maintain alphabetical sort when sorting on other criteria)
  • Extensibility via widget system
  • Cross-browser: IE 6.0+, FF 2+, Safari 2.0+, Opera 9.0+
  • Small code size



jQuery Autocomplete like Facebook With Demo

jQuery Autocomplete like Facebook With Demo

jQuery facebook autocomplete live demo

Following are the code snippet example for Autocomplete (similar the facebook autocomplete).

Code Example:
<link charset="utf-8" href="" media="screen" rel="stylesheet" type="text/css"></link>
        <script charset="utf-8" src="" type="text/javascript"></script>
        <script charset="utf-8" src="" type="text/javascript"></script>

JQuery Autocomplete similar to facebook</h1>
<div id="text">
<form accept-charset="utf-8" action="submit.php" method="POST">
<select id="select3" name="select3">
                <option class="selected" value="sleep">sleep</option>
                <option value="sport">sport</option>
                <option value="freestyle">freestyle</option>
            <br />
<input type="submit" value="Send" />
<script type="text/javascript">
          /** json_url data **/
        var jsonData=[{"key": "hello world", "value": "hello world"}, {"key": "movies", "value": "movies"}, {"key": "ski", "value": "ski"}, {"key": "snowbord", "value": "snowbord"}, {"key": "computer", "value": "computer"}, {"key": "apple", "value": "apple"}, {"key": "pc", "value": "pc"}, {"key": "ipod", "value": "ipod"}, {"key": "ipad", "value": "ipad"}, {"key": "iphone", "value": "iphone"}, {"key": "iphon4", "value": "iphone4"}, {"key": "iphone5", "value": "iphone5"}, {"key": "samsung", "value": "samsung"}, {"key": "blackberry", "value": "blackberry"}]
        /** json_url data **/
                    json_url: "",// This must be in your server
                    addontab: true,                   
                    maxitems: 2,
                    height: 2,
                    cache: true
        <div id="testme">

jQuery naming convention - jQuery tutorial for beginner

JQuery A fast, concise, library that simplifies how to traverse HTML documents, handle events, perform animations, and AJAX and do lot of more things in very simple and quick way..

For all this, Just include the jquery.js file.
<script src="//"></script>

jQuery naming convention - jQuery tutorial for beginner

JQuery most useful and very common functions used in the development
1) jQuery(this);// Current object
2) jQuery("p");// Select all the P tag
3)jQuery("");//Select all the P tag having class abc

4) jQuery("ul li:first");//select the first li of ul

5)jQuery("p").hide();// Hide the p tag

6) jQuery(document).ready(function(){

/*When you click the button first time, it will hide the div having class toggle and when click again will show.*/

7)jQuery("div#intro .head"); // select the class having "head" under div having id "intro"

8)jQuery("[hrefjQuery='.jpg']"); //select all href having link ending with jpg

9)jQuery("").append("greatinformations");;// Add the text "greatinformations" end the div having class abc

10) jQuery("").after("greatinformations"); /*Add the text "greatinformations" after the ending the div having class abc Enter code here.
Please note: Although no board code and smiley buttons are shown, they are still usable.*/

11)jQuery("div").animate({height:300},"slow"); //change all the div height to 300px

12) jQuery(this).css("background-color"); //get the background color of current html object

13)jQuery(this).css("background-color", 'blue' ); //set the background-color to blue of current html object

14)jQuery("div").animate({left:"100px"},"slow"); // Move the div to 100px

15)/*jQuery Callback:A callback function is executed after the current work is done eg. */

alert("The div is display now ");

16) jQuery("button.a").click(function(){
});  /* when click on button having class a will load the data from abc.text and upload to div */

17) jQuery("div").load('abc.txt','',function(){alert('hi')}); // after loading file abc.txt, alert the "hi" 

How to Select / Deselect All Checkboxes using jQuery

How to Select / Deselect All Checkboxes using jQuery
If you are developer and looking for a jQuery code-snippet that selects and de-selects multiple checkboxes by clicking “Select All” checkbox, like in, and Then you are at right place. 

This is very simple and most commonly used in web application and specially its used where there is multiple record listing. 

In Admin section,  this functionality is needed in every page, like User Listing, Product Listing, Album Listing  & images listing etc. 

When selected "Select All" checkbox, It will select all the checkbox under the main checkbox. 
If you de-select the "Select All", It will de-select all the checkbox under this main checkbox.

You can use below code and do the modification as per your requirement. This code is very useful not just in current web application but also for future.

select all checkbox jquery DEMO

Select All
Code Snippet
<script src="//"></script>

<script type="text/javascript"> 

jQuery(document).ready(function() {












<table border="1" rules="groups" style="width: 200pxpx;">

        <th><input id="checkbox_all" name="checkbox" type="checkbox" /></th> 

        <th>Select All</th> 


        <td><input class="chk" name="checkbox" type="checkbox" /></td> 



        <td><input class="chk" name="checkbox" type="checkbox" /></td> 



        <td><input class="chk" name="checkbox" type="checkbox" /></td> 



        <td><input class="chk" name="checkbox" type="checkbox" /></td> 



        <td><input class="chk" name="checkbox" type="checkbox" /></td> 



Thursday, 18 August 2016

How to get visitor location with JavaScript ?

How to get visitor location with JavaScript ?

Today there are lots Free/Paid API avaiable which give you client information.
Following are two example which give you client information like city, country, country code, ip, local date time, timezone etc with javascript.
Question: How to get visitor location javascript with
<script src=""></script>
$(document).ready( function() {
   $.getJSON("", function(result){


{  "ip": "",
  "country_code": "IN",
  "country_name": "India",
  "region_code": "PB",
  "region_name": "Punjab",
  "city": "Mohali",
  "zip_code": "",
  "time_zone": "Asia/Kolkata",
  "latitude": 30.78,
  "longitude": 76.69,
  "metro_code": 0

Question: How to get visitor location javascript with

<script src=""></script>
$(document).ready( function() {
   $.getJSON('', function(data){

  {"ip": "",
  "hostname": "No Hostname",
  "city": "Mohali",
  "region": "Punjab",
  "country": "IN",
  "loc": "30.7800,76.6900",
  "org": "AS17917 Quadrant Televentures Limited"

Wednesday, 20 January 2016

jQuery UI Interview Questions and Answers

 jQuery UI Interview Questions and Answers

Question: What is jQuery UI? It is JavaScript Library which is collection of jQuery widgets like datepicker, tabs, autocomplete etc. We can also add effects, interactions (drag, drop, resize) on widgets.

  Question: What widets are available in jQuery UI?
  1. Accordion
  2. Autocomplete
  3. Button
  4. Datepicker
  5. Dialog
  6. Menu
  7. Progressbar
  8. Selectmenu
  9. Slider
  10. Spinner
  11. Tabs
  12. Tooltip

Question: What are different effects available in jQuery UI
  1. Add Class
  2. Color Animation
  3. Easing
  4. Effect
  5. Hide
  6. Remove Class
  7. Show
  8. Switch Class
  9. Toggle
  10. Toggle Class

Question: In which language, JQuery UI is written?

Question: Is JQuery UI opensource?
Question: What is current stable version of JQuery UI?
1.11.4 / dated 11 March 2015

Question: From where we can download the jQuery UI

Question: Can we download custom widgets from jQuery UI
Yes, We can.

Question: How to add CSS property on last div?
$('div:last').css({backgroundColor: 'green', fontWeight: 'bolder'});

Question: What is $.noConflict()?
<script src="" type="text/javascript"></script>
<script type="text/javascript">

When we call to $.noConflict(). Old references of $ are saved during jQuery initialization, noConflict() simply restores them.

Question: Can we use another variable instead of $ in jQuery? If yes, How?
Yes, we can.
var jQ = jQuery.noConflict();
/** Now use jQ instead of $ **/
jQ( "div#pid" ).hide();

Question: How to remove close button on the jQuery UI dialog using CSS?
.ui-dialog-titlebar-close {
  visibility: hidden;

Question: How to remove close button on the jQuery UI dialog using JavaScript?
   closeOnEscape: false,
   open: function(event, ui) { $(".ui-dialog-titlebar-close", ui.dialog | ui).hide(); }

Question: How to initialize a dialog without a title bar?
var dialogOpts=[]
//Remove the title bar

Question: How to call Hook into dialog close event in jQuery UI?
$('div#contentId').on('dialogclose', function(event) {
     //console.log('closed event called');

Question: How to Download jQuery UI CSS from Google's CDN?

Question: How to "Change button text" in JQuery?
jQuery Version < 1.6
$("#elementId").attr('value', 'Save'); //versions older than 1.6

jQuery Version > 1.6
$("#elementId").prop('value', 'Save'); //versions newer than 1.6

Question: How can I disable a button in a jQuery ?
$('#divId').attr("disabled", true);

Question: How do I keep jQuery UI Accordion collapsed by default?
$("#divId").accordion({ header: "h4", collapsible: true, active: false });

Question: How to call a dragable widget?
// Make #draggable draggable
$(function () {

Question: How do I disable a jquery-ui draggable of widget?
//myObject is widget object.
myObject.draggable( 'disable' );

OR, you can set during the initalization
    draggable: false

How to remove JQuery UI Autocomplete Helper text?
.ui-helper-hidden-accessible { display:none; }

Question: How to set year in DatePicker?
    yearRange: '1950:2013', 
   changeMonth: true,
   changeYear: true,
   showButtonPanel: true,

Question: How to set current Date in Date Picker?
$(".datepickerClass").datepicker('setDate', new Date());

Question: How to Change Date Format in jQuery UI DatePicker?
var date = $('#datepickerDivId').datepicker({ dateFormat: 'dd-mm-yy' }).val();

Friday, 1 January 2016

jQuery Mobile interview questions and answers

jQuery mobile interview questions and answers

jQuery Mobile is a UI framework which is written in javaScript language and used for creating mobile web applications. It works on all popular smartphones and tablets. jQuery Mobile uses HTML5 & CSS3.

What is Initial release of JQuery Mobile?
October 16, 2010

Question: What is Latest version of jQuery Mobile?
Version: 1.4.5
Dated: October 31, 2014

Question: In which language, jQuery mobile is written?

Question: Where it is used?
It is "Mobile application framework" which is used for creating mobile web applications.

Question: What is offical website of jQuery Mobile?

Question: What are Features of jQuery Mobile?
  • Compatible with all major desktop browsers as well as all major mobile platforms (Android, iOS, Windows Phone, Blackberry, WebOS, Symbian)
  • Built on top of jQuery core.
  • Lightweight to optimize speed.
  • The same underlying codebase will automatically scale to any screen.
  • HTML5-driven.
  • AJAX-powered navigation with animated page.
  • UI widgets

Question: Why Use jQuery Mobile?
1. Write Less, Do more
2. Its works on Android, Blackberry, iOS and Iphone
3. Its optimized

Question: Describe few HTML tags used in jQuery Mobile?
data-role="page": Page displayed in the browser.
data-role="header": Creates a toolbar at the top of the page.
data-role="main": Content of the page, like text, images, buttons and forms etc.
"ui-content": Adds extra padding and margin inside the page content
data-role="footer": creates a toolbar at the bottom of the page

Question: How to Add Back Button?
<a class="ui-btn" data-rel="back" href="">Go Back</a>

Question: What is jQuery Mobile Themeing?
jQuery Mobile provides a powerful theming that allows developers to customize color schemes & CSS aspects of UI features.

Wednesday, 16 September 2015

jQuery Ajax Interview Questions and Answers for Experienced

jQuery Ajax Interview Questions and Answers for Experienced

Question: What is the difference between jQuery.get() and jQuery.ajax()?
$.get( "/ajax/add-user", { name: "Arun", company: "", gender:"Male" } );
$.get executes an Ajax request with using of GET Method.

    type: "POST",
    url: "/ajax",
    data: "name=Arun&",
    success: function(msg){

$.ajax you full control over the Ajax request. In this you can use any method like GET or POST. I think you should use this only, if the other methods did not fulfill your requirement.
You can do lot of customization in this like caching and Ajax method etc

Question: What is the use of jQuery load method?
It is AJAX method which is used to load the data from a server and assign the data into the element without loading the page.

Question:What are the security issues with AJAX?
  1. Source code written in ajax easily visiable.
  2. Attrackers can send the the data to same API Call
  3. Attrackers can view the Request/Response in Ajax call.
  4. Attacker can view the full response and can hit and trial.

Question: How many types of ready states in ajax?
0: Request not initialized
1: Server connection established
2: Request received
3: Processing request
4: Request finished and response is ready

Question: List Some Popular Ajax Frameworks?.
  1. jQuery.
  3. Prototype
  4. MooTools
  5. ExtJS
  6. Qooxdoo
  7. Yahoo! UI Library (YUI)
  8. MochiKit
  9. Midori
  10. The Dojo Toolkit

Question: What exactly is the W3C DOM?
The W3C Document Object Model (DOM) is defined by the W3C.
The DOM is a platform and language-neutral interface that allows programs and scripts to dynamically access/update the content of a document.

Question: What is the XMLHttpRequest object in AJAX?
It is way to update the web content from server without reloading the page.

Question: How can we abort the current XMLHttpRequest in AJAX?
use abort() function. For Example:
var xhr;    
xhr = $.ajax({
    url: 'ajax/get-user-details/user_id/3',
    success: function(data) {

//Abort the Ajax call
if(xhr && xhr.readystate != 4){

Question: How to cancel all the active ajax call?
Every time you create an ajax request you should use a variable to store it, you can use array object to store multiple ajax.
Now you can use abort() function to abort each ajax call.

Question: How to debug Ajax call
You can use debug tools of browser.
like firebug in Mozilla.
Inspect element in Google Chrome

Question: How to convert an object to a string?
var javascriptObject = {name: "Web", "URL": ""};
JSON.stringify(javascriptObject, null, 2);

Question: How to convert an string to a object?
var javascriptObject = '{name: "Web", "URL": ""}';
JSON.parse(javascriptObject, null, 2);

Question: How can I add a custom HTTP header to ajax request with js or jQuery?
    url: '/ajax/get-user-details/user_id/3',
    headers: { 'x-my-custom-header': 'some value' },
    success: function(data) {

Question: How to determine if ajax timeout error comes?
     url: '/ajax/get-user-details/user_id/3',
    type: "GET",
    dataType: "json",
    timeout: 1000,
    success: function(data) { 
    error: function(x, t, m) {
        if(t==="timeout") {
            console.log("got timeout");
        } else {

Question:How to send an https ajax call on http page?
Add the Access-Control-Allow-Origin header from the server

Friday, 17 July 2015

Jquery Interview Questions and Answers for experienced

jquery interview questions and answers for experienced
Question: What is jQuery?
jQuery is a fast, small and feature-rich JavaScript library.
jQuery makes things like HTML document traversal and manipulation, animationevent handling and Ajax much simpler with an easy-to-use API.
It works across a multitude of browsers.

Question: What is Ajax?
Ajax( Short form of Asynchronous JavaScript and XML) is a Web development techniques used on the client-side to create Synchronous OR asynchronous Web applications. It is used to get the data from server without refresh the page.

Question: What is Iframe?
Iframe is an HTML document embedded inside another HTML document on a website. We can embed one OR many iframe in one website.

Question: What is element in HTML?
An HTML element is an individual component of an HTML document or web page.
For example, p,div,span etc know as element.
when these surrounded by angle brackets know as HTML Tags.

Question: What is event in jQuery? Doing any thing, known as event.
For Example, Click event, mouseover event, blur event, double click event etc.

Question: What is jQuery event?
A jQuery object is array-like which means that it contains zero or more indexes.

Question: How to parse a JSON String?
var obj = jQuery.parseJSON( '{ "name": "John" }' );

Question: How to communicate between iframe and the parent site?
With same domain and same port/protocol
you can use window.opener to change in parent window from child window.
you can use document.getElemetById('#iframeId') to change in child window from parent window.
With different domain OR different port/protocol
You have to use cross-document messaging.

Question: How can I select an element by name or class or id with jQuery?
Select by name

Select by class name

Select by classId

Question: How to show the preview an image before it is uploaded to server?
To show the preview you need to use "FileReader" javascript function.
See Demo:

Question: How to get html tags from string?
var re = /(<([^>]+)>)/ig; 
    var str = '


'; var m; while ((m = re.exec(str)) !== null) { if (m.index === re.lastIndex) { re.lastIndex++; } } console.log(re);

Question: What is use $.each? Give examples?
It is similar to foreach in jQuery.
you can use $.each for normal array OR list of elements. For Example:
$('a.myclass').each(function(index, value){

var numberArray = [0,1,2,3,4,5];
jQuery.each(numberArray , function(index, value){
     console.log(index + ':' + value); 

Question: What's the difference between jquery.js and jquery.min.js?
Both are same.
only difference jquery.min.js is minified file which have no space, tab.

Question: How to add Email Validation in jQuery?
function IsValidEmail(email) {
  var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
  return regex.test(email);
console.log(IsValidEmail('[email protected]'));
console.log(IsValidEmail('[email protected]'));

Question: How to get nth jQuery element?
use eq function.

Question: How to remove a row from table?

Question:How to bind shortcut-keys with jQuery?
To bind Ctrl+f to a functionName.
$(document).bind('keydown', 'ctrl+f', functionName);

You can check also:

Question: How to convert array to JSON?
You can use stringify.
var yourArray = Array('1','2','3','4');
var myJsonString = JSON.stringify(yourArray);

Question: How to check if a div exists with jquery?
if($("div#idName" + name).length > 0) {
  /** It is exist **/

Question: How to call a function after 3 seconds?
/** Do here **/

/** Do here **/    
  }, 3000);

Question: How to prevent caching in Ajax?
After loading of jQuery, add the below code at the top of all ajax call.
$.ajaxSetup({ cache: false });

Saturday, 11 April 2015

How can I check DOM is ready in jQuery

How can I check DOM is ready in jQuery

Question: What is DOM?
The Document Object Model (DOM), is a model for representing and interacting with an XML, XHTML and HTML document.

Question: What is meaning of DOM is ready?
DOM is ready means html, images, css and java-Script are loaded fully.

Question: Why need to check if DOM is ready OR NOT?
Some times, we need to do the some modification in html tags like p,div and image etc.
We can change the DOM only after if DOM is loaded.

Following are 3 methods to check DOM() is fully loaded?
Method 1:
      //consol.log('DOM IS FULLY loaded');


Method 2:
  //consol.log('DOM IS FULLY loaded');

Method 3:
if ( jQuery.isReady ) {  
    //consol.log('DOM IS FULLY loaded');

Wednesday, 25 March 2015

How to add new row in existing table using jQuery

How to add new row in existing table using jQuery

I have following existing table

<table id="myTestTable"> <tbody> <tr>.......</tr> <tr>.......</tr> <tr>.......</tr> <tr>.......</tr> </tbody> </table>

Currently, It have Total 4 Rows.
I want to add one more row, Just after the last table row. Which should look like below:

<table id="myTestTable"> <tbody> <tr>.......</tr> <tr>.......</tr> <tr>.......</tr> <tr>.......</tr> <tr>.......</tr> </tbody> </table>

Now, how can I add new table-row in existing table in single line?.

Step 1: Add jQuery file in webpage.
<script src="//"></script>

Step 2: Just add following script when you want to add new table row in existing table.
$('table#myTestTable tr:last').after('...');
It will add one new row in exiting table @ the end each time you call this script.

Monday, 23 March 2015

How to Include a JavaScript file in another JavaScript file?

How to Include a JavaScript file in another JavaScript file?

Including a javascript file in another javascript file is common in web development.
Because many times we include the javascript file at run time on the behalf of some conditions.

So, we can achieve this using javascript as well as using jQuery.

Method 1: Use JavaScript to include another JavaScript file.
Step 1: Add following function in web page.
function loadScript(url)
    var head = document.getElementsByTagName('head')[0];
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = url;

Step 2:just call the below loadScript function, Where you want to include the js file.

Method 2: Use jQuery to include another javasScript file .
Step 1: Add jQuery File in your webpage.
<script src="//"></script> Step 2: Just call the  getScript  function functions.

Saturday, 21 March 2015

How can I get query string values in JavaScript and jQuery?

How can I get query string values in JavaScript and jQuery?

I want to get the values from the Query String (means from URL), values are dynamic but query string variable is constant.

Suppose, I have following URL:

Now, I want to get the value of following query string.
id //currently it is 10, but it is dynamic.
c //currently it is country, but it is dynamic.

Solution 1: Get the value of query string with JavaScript.
Step 1: Add following javaScript function in your page.
function getParam(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        result = regex.exec(;
    return result === null ? "" : decodeURIComponent(result[1].replace(/\+/g, " "));

Step 2: Use getParam function to get the query string values. See below:

Solution 2: Get the value of query string with jQuery.
Step 1: Add jQuery File in your webpage.
<script src="//"></script>

Step 2: Add following jQuery function in web page.
  $.getParamJquery = function(name, url) {
      if (!url) {
       url = window.location.href;
      var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(url);
      if (!results) { 
          return undefined;
      return results[1] || undefined;

Step 3: Use getParamJquery function to get the query String values. See below: