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

Pages

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.
$("#txt1").val("Hello");
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.
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjK3yXBJd0zUPi0cVpNSLT68MPz7wFQUosefBoRFK_n4lsWkOlOG0aHl5EQ-m1RNzYvX9_JGoPZAyo_YpVDEGwT6X-A1aBEJKNjFwRg24qlurPkycg_f86N0AKfpMtWSGSAXwozIG8sAA/s1600/1.jpg

Below this is view of Jquery.min.js file (compressed and minified).
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg9NuAS8Zks7E5syfZbcWFvXd5qRTHI59_-wM5G3LoAj5Cd5op5opu744PNgScikdRppmUmVLhGO_YERZ42mp5OWpaHsLiOgKNe1gqmFKux8tW3bWdjxDP0ASHmQfTpiOFhBUovHgzetQ/s1600/2.jpg

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.
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhquFKNpJ-gXoqUcRsZrh2wLfn7DHxdxz0d3BP6jRZ6ltZgCoiOrEbulA3PXVctaHhfHM5WZYlunhTZp1YWa35LQphX8jwzzpyvpKqDyLHVqjZtCJeMY04RgyVu3rrc0uieakv4dA8H1w/s1600/3.jpg

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’.
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiChPoKUDLy34c1RpglGSbPvE2Xa86bqxCH6cwGsWuyxbbJqheF25sEW-BczBwfhd9vHx7ROVB9bRT3os2eT2z4e95AspYxuMns7E1wtAcuk97tCqm4DFn2cZeFjgCr67Nw210gpov8DQ/s1600/4.jpg

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.
$.noConflict();
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.
$("p").hide();
Select by ID
$("#Text1").val("Shiv");
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.
Yes.
Below is a simple code which attaches a function to click event of a button.
$("button").click(function(){
$("p").toggle();
});
Below is one more example where we have attached the a function to a mouse enter event of a paragraph.
$("#p1").mouseenter(function(){
  alert("You entered p1!");
});
$("li").filter(".middle").addClass("selected");

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):
 $.ajax({
     url: 'pcdsEmpRecords.php',
     success: function(response) {
        alert(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() {
     $.ajax({
            url: 'pcdsEmpRecords.php',
            success: function(response) {
             // update div id Results 
             $('#results').html(response);
         }
     });
 }
 
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
 $("#pcds").removeAttr('disabled');
 
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
 $("#pcds").removeAttr('checked');
 
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:
 $("#pcdsselect").val();
 // => 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
<html>

Combine Date Values

<body>

</
body>
</
html>


jQuery.holdReady()http://www.learnjavascript.co.uk/jq/reference/core/holdready.html
Hold or release the jQuery ready event.
Shorthand version $.holdReady()

Description

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

Syntax

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

Parameters

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

true - Hold the jQuery ready event. 

false - Release the jQuery ready event.

Return

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"  
         "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>jQuery Core & Internals</title>
         
  
  <script type="text/javascript" src="jquery-1.10.1.min.js"></script>
 
  
  <script type="text/javascript">
    $.holdReady(true);
    alert('jQuery ready event being released);
    $.holdReady(false);
    $(function(){ // jQuery(document).ready(function(){
      // Other jQuery stuff for after ready()
    });
  </script>
</head>
<body>
</body>
</html>
 
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:
1
$('#<%=Label1.ClientID%>').text();
Set label value:
1
$('#<%=Label1.ClientID%>').text("New Value");
Get Textbox value:
1
$('#<%=TextBox1.ClientID%>').val();
Set Textbox value:
1
$('#<%=TextBox1.ClientID%>').val("New Value");
Get Dropdown value:
1
$('#<%=DropDownList1.ClientID%>').val();
Set Dropdown value:
1
$('#<%=DropDownList1.ClientID%>').val("New Value");
Get text of selected item in dropdown:
1
$('#<%=DropDownList1.ClientID%> option:selected').text();
Get Checkbox Status:
1
$('#<%=CheckBox1.ClientID%>').attr('checked');
Check the Checkbox:
1
$('#<%=CheckBox1.ClientID%>').attr('checked',true);
Uncheck the Checkbox:
1
$('#<%=CheckBox1.ClientID%>').attr('checked',false);
Get Radiobutton Status:
1
$('#<%=RadioButton1.ClientID%>').attr('checked');
Check the RadioButton:
1
$('#<%=RadioButton1.ClientID%>').attr('checked',true);
Uncheck the RadioButton:
1
$('#<%=RadioButton1.ClientID%>').attr('checked',false);
Disable any control:
1
$('#<%=TextBox1.ClientID%>').attr('disabled', true);
Enable any control:
1
$('#<%=TextBox1.ClientID%>').attr('disabled', false);
Make textbox read only:
1
$('#<%=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.
1
    2
        
  • 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
    $('li').get(2);
    2
    $('li').eq(2);
    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. 
    1
    $(document).ready(function () {
    2
      $('li').eq(2).css('background-color', 'red'); //Works

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




    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

    • काश - काश मुझे भी पीने की आदत होती,मैं कब का मुर्दा हो गया होता। छुटकारा मिलता आज के आतंकवाद से, किसी संतान भूमि में सो गया होता। मेरा एतबार कौन करेगा, मैंने मुर...
      2 months ago
    • काश - काश मुझे भी पीने की आदत होती,मैं कब का मुर्दा हो गया होता। छुटकारा मिलता आज के आतंकवाद से, किसी शमशान भूमि में सो गया होता। मेरा एतबार कौन करेगा, मैंने मुर...
      2 months ago
    • Kumaon University Nainital B.Ed entrance exam test result 2012 - कुमाऊँ विश्वविधालय, नैनीताल (उत्तराखण्ड)
      10 years ago