/* ------------------------ My Meta Content Here SEO ------------------------ */


Main Menu

Tuesday, October 14, 2014

JQuery Introduction

Jquery is a reusable javascript library which simplifies javascript coding. So rather than writing lengthy javascript code as below.
document.getElementById("txt1").value = "hello";
By jquery the above javascript code is now simplified as below.
No, Jquery is not meant to replace javascript. Jquery is a library while javascript is a language. Jquery sits on the top of javascript to make your development easy.
You need to download Jquery.js file from jquery.com and include the same in your web pages. The jquery files are named with version number like “jquery-1.4.1.js” where 1.4.1 is the version of the JS file. So at the top of your web page you need to include the javascript as shown in the below code.
In CDN multiple copies of the website is copied on different geographical servers. When users request website content which have CDN enabled depending on their geographical location content is served from the nearest geographical location server of the user.
So if a user is from India, the Indian CDN server will serve request for Indian users. This leads to faster delivery and good backup in case there are issues.
There are two popular CDN’s Microsoft and google.
If you want to reference google CDN Jquery files you can use the below script.
If you want to use Microsoft CDN you can use the below javascript.
Many times it’s possible that Microsoft and google servers can go down for some time. So in those situations you would like your page to reference jquery files from local server.
So to implement a CDN fallback is a two-step process: -
First reference the CDN jquery. In the below code you can see we have reference Microsoft CDN jquery file.
http://ajax.microsoft.com/ajax/jquery/jquery-1.9.1.min.js ">
Now if Microsoft CDN is down then the Jquery value will be “undefined”. So you can see in the below code we are checking if the Jquery is having “undefined” value then do a document write and reference your local Jquery files.
if (typeof jQuery == 'undefined')
  document.write(unescape("%3Cscript src='Scripts/jquery.1.9.1.min.js' type='text/javascript'%3E%3C/script%3E"));
Below is the full code for the same.

First thing both the files provide the same jquery functionalities. One is a long version and the other is compressed / minified version. The minified version is compressed to save bandwidth and space by compressing and removing all the white spaces.
Below is the view of Jquery.js.

Below this is view of Jquery.min.js file (compressed and minified).

When you are doing development use “jquery.js” file because you would like to debug, see the javascript code etc. Use “Jquery.min.js” for production environment. In production / live environment we would like to consume less bandwidth, we would like to our pages to load faster.
This file you can include if you want to enable intellisense in visual studio for Jquery.

Jquery syntax structure can be broken down in to four parts: -
  • All Jquery commands start with a “$” sign.
  • Followed by the selection of the HTML element. For example below is a simple image where we are selecting a HTML textbox by id “txt1”.
  • Then followed by the DOT (.) separator. This operator will separate the element and the action on the element.
  • Finally what action you want to perform on the HTML element. For instance in the below Jquery code we are setting the text value to “Hello JQuery’.

The “$” sign is an alias for jquery.
There are many javascript frameworks like MooTools, Backbone, Sammy, Cappuccino, Knockout etc. Some of these frameworks also use “$” sign so this can lead to conflict with Jquery framework.
So you can use the “noConflict” method and release the jquery “$” sign as shown in the below code.
jQuery("p").text("I am jquery and I am working…");
You can also create your own jquery shortcut as shown below.
var jq = $.noConflict();
jq("p").text("I am invoked using jquery shortcut…");
You can select Jquery elements in the following ways: -
Select all
Below is a simple code snippet which selects all paragraph tags and hides them.
Select by ID
Select using Equal method
Select using Find method
Select using Filter method
“Document.Ready” event occurs once the complete HTML DOM is loaded. So the next question is when do we actually need this event?. Consider the below simple code where we are trying to set a text box “text1” with value “Sometext”.
Now at the point when Jquery code tries set the textbox value , at that moment that text box is not available in the HTML DOM. So it throws an exception for the same.
So we would like to execute the Jquery code which sets the textbox value only when all the HTML objects are loaded in DOM. So you can replace the code of setting text box value to something as shown below.
Below is a simple code which attaches a function to click event of a button.
Below is one more example where we have attached the a function to a mouse enter event of a paragraph.
  alert("You entered p1!");

Whatis the use of $ Symbol ? $ Symbol is just replacement of jquery means at the place of $ you may use jquery hence $ symbol is used for indication that this line used for jquery
How to get the server response from an AJAX request using Jquery? 
When invoking functions that have asynchronous behavior We must provide a callback function to capture the desired result. This is especially important with AJAX in the browser because when a remote request is made, it is indeterminate when the response will be received.
Below an example of making an AJAX call and alerting the response (or error):
     url: 'pcdsEmpRecords.php',
     success: function(response) {
     error: function(xhr) {
        alert('Error!  Status = ' + xhr.status);
How do you update ajax response with id " resilts" 
By using below code we can update div content where id 'results' with ajax response
 function updateStatus() {
            url: 'pcdsEmpRecords.php',
            success: function(response) {
             // update div id Results 
How do You disable or enable a form element?  There are two ways to disable or enable form elements.Set the 'disabled' attribute to true or false:
 // Disable #pcds
 $('#pcds').attr('disabled', true);
 // Enable #pcds
 $('#pcds').attr('disabled', false);
Add or remove the 'disabled' attribute:
 // Disable #pcds
 $("#pcds").attr('disabled', 'disabled');
 // Enable #x
How do you check or uncheck a checkbox input or radio button?  There are two ways to check or uncheck a checkbox or radio button.
Set the 'checked' attribute to true or false.
 // Check #pcds
 $('#pcds').attr('checked', true);
 // Uncheck #pcds
 $('#pcds').attr('checked', false);
Add or remove the 'checked' attribute:
 // Check #pcds
 $("#pcds").attr('checked', 'checked');
 // Uncheck #pcds
How do you get the text value of a selected option?  Select elements typically have two values that you want to access. First there's the value to be sent to the server, which is easy:
 // => 1
The second is the text value of the select. For example, using the following select box:
If you wanted to get the string "Mr" if the first option was selected (instead of just "1"), you would do that in the following way: $("#mpcdsselect option:selected").text();
 // => "Mr"

JQuery Bind() And Unbind() Example
jQuery bind() function is used to attach an event handler to elements, while the unbind() is used to detached an existing event handler from elements.

Get current month and year in jQuery

getFullYear() method return current year and (getMonth() + 1) method return the current monthwhereas getDate() method return current day in jQuery.

Current year in jQuery

getFullYear() return the current year.

Current month in jQuery

getMonth() + 1 return the current month. Be careful getMonth() not return the current month, So always use getMonth() + 1 instead of getMonth()

Current day in jQuery

getDate() return the current day.
  jQuery With Example

Translate the Date().getMonth() to month name

Combine Date Values



Hold or release the jQuery ready event.
Shorthand version $.holdReady()


The jQuery.holdReady() method holds or releases the execution of the jQuery ready event.


jQuery.holdReady( hold ) Hold or release the execution of the jQuery ready event.


A boolean representing whether to hold or release the jQuery ready event

true - Hold the jQuery ready event. 

false - Release the jQuery ready event.


jQuery.holdReady( hold ) Example

Hold or releases the execution of the jQuery ready event.
jQuery allows us to fire off events as soon as the DOM is ready by using the .ready() method. There are also situations where we may want to delay execution of the jQuery ready event, for example to load plugins. We can then release the jQuery ready event after our conditions are met giving us complete control. We use thejQuery.holdReady() method to achieve this. When using this method its best to ensure its called early within the HTML document and before the ready event has already fired.
A good place to put this method is in the <head></head> HTML element after the import of the jQuery library and before any other JavaScript and jQuery that is to be executed. Calling this method after the ready event has already fired will have no effect.
When you entered this page an alert box was shown informing you that the jQuery ready event is about to fire. When you closed the alert box we released the jQuery ready event. Simplified HTML code is shown below so you can see its placement:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"  
<html xmlns="http://www.w3.org/1999/xhtml">
  <title>jQuery Core & Internals</title>
  <script type="text/javascript" src="jquery-1.10.1.min.js"></script>
  <script type="text/javascript">
    alert('jQuery ready event being released);
    $(function(){ // jQuery(document).ready(function(){
      // Other jQuery stuff for after ready()
All we see on page entry is the alert box as we haven't released the ready event which is the first code in the <head> </head> HTML element after all the imports. Therefore at this point no <body> </body> HTML elements have been rendered to the page.

Useful jQuery code example for ASP.NET controls
Get label value:
Set label value:
$('#<%=Label1.ClientID%>').text("New Value");
Get Textbox value:
Set Textbox value:
$('#<%=TextBox1.ClientID%>').val("New Value");
Get Dropdown value:
Set Dropdown value:
$('#<%=DropDownList1.ClientID%>').val("New Value");
Get text of selected item in dropdown:
$('#<%=DropDownList1.ClientID%> option:selected').text();
Get Checkbox Status:
Check the Checkbox:
Uncheck the Checkbox:
Get Radiobutton Status:
Check the RadioButton:
Uncheck the RadioButton:
Disable any control:
$('#<%=TextBox1.ClientID%>').attr('disabled', true);
Enable any control:
$('#<%=TextBox1.ClientID%>').attr('disabled', false);
Make textbox read only:
$('#<%=TextBox1.ClientID%>').attr('readonly', 'readonly');

jQuery: Difference between eq() and get()

In this post, find out what is the difference between jQuery  eq() and  get() method. Both the methods are used to find and select single element from set of elements and they both return single "element". And they both accept single int type parameter, which denotes index.

Related Post: 

·                     Difference between $(this) and 'this' in jQuery
·                     empty() vs remove() vs detach() - jQuery
·                     jQuery - bind() vs live() vs delegate()

For example, take a look at below HTML. There is a
    element with 5
  • elements.
  • list item 1

  • 3
  • list item 2
  • 4
  • list item 3

  • 5
  • list item 4
  • 6
  • list item 5

  • 7
    And to select 3rd
  • element, use either get() or eq() and pass 2 as index. Keep in mind that index is zero-based.
  • 1
    In the above code, both will return the 3rd
  • element. But then what is the difference between 2.

  • eq() returns the element as a jQuery object. This method constructs a new jQuery object from one element within that set and returns it. That means that you can use jQuery functions on it.

    get() return a DOM element. The method retrieve the DOM elements matched by the jQuery object. But as it is a DOM element and it is not a jQuery-wrapped object. So jQuery functions can't be used. 
    $(document).ready(function () {
      $('li').eq(2).css('background-color', 'red'); //Works

      $('li').get(1).css('background-color', 'red'); // Error. Object # has no method 'css'

    Jquery get data on XHR error

    In the:
    error: function (xhr, tst, err) {
        $.log('XHR ERROR ' + XMLHttpRequest.status);
    you can use
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        $.log('XHR ERROR ' + XMLHttpRequest.status);
        return JSON.parse(XMLHttpRequest.responseText);
    to get the JSON response in in event of an error.

    No comments:

    Post a Comment

    My Blog List