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


Demo


Documentation


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="//www.emposha.com/demo/fcbkcomplete_2/style.css" media="screen" rel="stylesheet" type="text/css"></link>
        <script charset="utf-8" src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.min.js" type="text/javascript"></script>
        <script charset="utf-8" src="//www.emposha.com/demo/fcbkcomplete_2/jquery.fcbkcomplete.js" type="text/javascript"></script>

        <h1>
JQuery Autocomplete similar to facebook</h1>
<div id="text">
</div>
<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>
            </select>
            <br />
<input type="submit" value="Send" />
        </form>
<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 **/
        
            $(document).ready(function(){                
                $("#select3").fcbkcomplete({
                    json_url: "http://www.emposha.com/demo/fcbkcomplete_2/data.txt",// This must be in your server
                    addontab: true,                   
                    maxitems: 2,
                    height: 2,
                    cache: true
                });
            });
        </script>
        
        <div id="testme">
</div>



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="//ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></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("p.abc");//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(){
jQuery("button").click(function(){
jQuery("div.toggle").toggle();
});

});: 
/*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("p.abc").append("greatinformations");;// Add the text "greatinformations" end the div having class abc

10) jQuery("p.abc").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. */

jQuery("button").click(function(){
jQuery("div.class").show(300,function(){
alert("The div is display now ");
});.

16) jQuery("button.a").click(function(){
jQuery("div").load('abc.txt');
});  /* 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 Gmail.com, rediffmail.com and yahoo.com. 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
Name2
Name3
Name4
Name5
Name6
Code Snippet
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<script type="text/javascript"> 

jQuery(document).ready(function() {

    jQuery('#checkbox_all').click(function(){ 
        
        if($(this).is(":checked")){ 
            jQuery('input[type="checkbox"].chk').each(function(){ 

                jQuery(this).prop("checked",true);

            });         

        }else{ 

            jQuery('input[type="checkbox"].chk').each(function(){ 

                jQuery(this).prop("checked",false);

            });                 

        } 

     

    }); 

}); 

</script> 
<table border="1" rules="groups" style="width: 200pxpx;">
<tbody>
<tr> 

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

        <th>Select All</th> 

    </tr>
<tr> 

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

        <td>Name2</td> 

    </tr>
<tr> 

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

        <td>Name3</td> 

    </tr>
<tr> 

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

        <td>Name4</td> 

    </tr>
<tr> 

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

        <td>Name5</td> 

    </tr>
<tr> 

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

        <td>Name6</td> 

    </tr>
</tbody></table>





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 freegeoip.net?
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready( function() {
   $.getJSON("http://freegeoip.net/json/", function(result){
       console.log(result);                        

       });
   });

Output
{  "ip": "112.196.3.177",
  "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 ipinfo.io?

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready( function() {
   $.getJSON('http://ipinfo.io', function(data){
    console.log(data)
  })
    }); 
</script>

Output
  {"ip": "112.196.3.177",
  "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?
JavaScript


Question: Is JQuery UI opensource?
Yes.
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
https://jqueryui.com/


Question: Can we download custom widgets from jQuery UI
Yes, We can.
https://jqueryui.com/download/


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



Question: What is $.noConflict()?
<script src="https://code.jquery.com/jquery-1.6.2.js" type="text/javascript"></script>
<script type="text/javascript">
$.noConflict()
</script>

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?
$("#div2").dialog({
   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=[]
$("#divId").dialog(dialogOpts);
//Remove the title bar
$(".ui-dialog-titlebar").hide();



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?
Uncompressed: http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.js
Compressed: http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js



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 () {
        $("#draggableDivId").draggable();
});



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
$("#yourDialogId").dialog({
    draggable: false
});



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



Question: How to set year in DatePicker?
 $(".datepickerClass").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?
JavaScript


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?
http://jquerymobile.com/


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="https://www.blogger.com/blogger.g?blogID=5911253879674558037#">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: "web-technology-experts-notes.in", gender:"Male" } );
$.get executes an Ajax request with using of GET Method.

$.ajax({
    type: "POST",
    url: "/ajax",
    data: "name=Arun&company=web-technology-experts-notes.in&gender=male",
    success: function(msg){
       console.log(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.
  2. script.aculo.us
  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) {
        console.log(data);
    }
})
    
fn();

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



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": "http://www.web-technology-experts-notes.in/"};
JSON.stringify(javascriptObject, null, 2);



Question: How to convert an string to a object?
var javascriptObject = '{name: "Web", "URL": "http://www.web-technology-experts-notes.in/"}';
JSON.parse(javascriptObject, null, 2);



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



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


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




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" }' );
console.log( obj.name);



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
console.log($('div[name=divname]'));

Select by class name
console.log($('div.className'));

Select by classId
console.log($('div#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:http://jsfiddle.net/LvsYc/


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

Hello!

'; 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){
      console.log($(this).attr('href'));
});

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('myvalidemail@domain.com'));
console.log(IsValidEmail('myInvalidemail@'));
console.log(IsValidEmail('myInvalidemail#domain.com'));



Question: How to get nth jQuery element?
use eq function.
console.log($("div.myclass:eq(2)")); 



Question: How to remove a row from table?
$('tr#myTableRowId').remove();
OR
$('tr.myTableRowClass').remove();


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: http://github.com/jeresig/jquery.hotkeys


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?
setTimeout(
  function(){
/** 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:
 jQuery(document).ready(function(){ 
      //consol.log('DOM IS FULLY loaded');

  });

Method 2:
$(function(){
  //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?.

Soltion:
Step 1: Add jQuery file in webpage.
<script src="//code.jquery.com/jquery-1.11.2.min.js"></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;
    head.appendChild(script);
}

Step 2:just call the below loadScript function, Where you want to include the js file.
 loadScript('/js/jquery-1.7.min.js');



Method 2: Use jQuery to include another javasScript file .
Step 1: Add jQuery File in your webpage.
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script> Step 2: Just call the  getScript  function functions.
 jQuery(document).ready(function(){
    $.getScript('/js/jquery-1.7.min.js');
});




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:
http://www.example.com/country.php?id=10&c=country

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(location.search);
    return result === null ? "" : decodeURIComponent(result[1].replace(/\+/g, " "));
}

Step 2: Use getParam function to get the query string values. See below:
console.log(getParam('id'));
console.log(getParam('c'));



Solution 2: Get the value of query string with jQuery.
Step 1: Add jQuery File in your webpage.
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>

Step 2: Add following jQuery function in web page.
jQuery(document).ready(function(){
  $.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:
jQuery(document).ready(function(){
  console.log($.getParamJquery('id'));   
  console.log($.getParamJquery('c'));
}