Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

jQuery Examples

This article talk about some jQuery examples such as Setting Drop Down Value, slideToggle Example, ajaxError Event Example, Setting Icon in Drop Down List Box, Scrolling a HTML Page.

jQuery is a light weight JavaScript library designed to simplify the client side scripting of HTML. It is “write less, do more” library which is free and open software.

In this article I’m going to cover following topics with demonstrative examples:

  • Setting Drop Down Value
  • slideToggle Example
  • ajaxError Event Example
  • Setting Icon in Drop Down List Box
  • Scrolling a HTML Page

Note: In all the following examples the CDN link for jQuery library in the HTML page, which should be declared inside the head section:

<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
</head>

Setting Drop Down Value

This section explains how to set drop down box value in jQuery. In the following example, we are using $(“#id_name”).val(); to set dropdown list value. If we need to set a particular value in the drop down box, then use $(“#id_name”).val(“value_name);.

The following example demonstrates setting of drop down value, disabling and enabling of value in the drop down list.

Listing 1: dropdownexample.html

<!doctype html>
<head>
<title>JQuery Text Selector</title>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
<style>
#fruits{
background:cyan;
}
</style>
<script type="text/javascript">
          $(document).ready(function(){
           $("#my_val").click(function(){
		alert($("#fruits").val());
            });
	$("#fruit1").click(function(){
	$("#fruits").val("apple");
	});
	$("#fruit2").click(function(){
	 $("#fruits").val("banana");
	});
	$("#disable_grapes").click(function(){
	 $("#fruits option[value='grapes']").attr("disabled",true);
	});
	$("#enable_grapes").click(function(){
	 $("#fruits option[value='grapes']").attr("disabled",false);
	});
});
</script>
<body>
<select id="fruits">
      <option value="None" style="background-color: Gray;">--Select--</option>
      <option value="apple" style="background-color: Brown;">Apple</option>
      <option value="banana" style="background-color: Pink;">Banana</option>
      <option value="grapes" style="background-color: Orange;">Grapes</option>
</select><br><br>
<input type="button" value="Click to see selected value" id="my_val">
<input type="button" value="Select Apple" id="fruit1">
<input type="button" value="Select Banana" id="fruit2">
<input type="button" value="Disable Grapes" id="disable_grapes">
<input type="button" value="Enable Grapes" id="enable_grapes">
</body>
</html>

The details of the above code as below:

  • The … is used for creating a drop down list with option tag that defines available options in the list and code uses id selector “fruits” to display particular value when user selects from the list.
  • We have used the code inside $(document).ready which is an event which fires up when the document is ready. It will run once the page document object model is ready for JavaScript code to execute.
  • $("#my_val").click(function(){alert($("#fruits").val());}: This function defines the click method, which occurs when user clicks on the button (Click to see selected value). An alert message will get displayed with the selected value (in the drop down list) .
  • $("#disable_grapes").click(function(){$("#fruits option[value='grapes']").attr("disabled",true);}: This function disables a particular value (by setting disabled attribute to true) in the drop down list when the user clicks the button (Disable Grapes). Here we are disabling the value for grapes; this value appears disabled and does not respond to user input. On similar lines $("#enable_grapes").click(function(){$("#fruits option[value='grapes']").attr("disabled",false);} enables the value for grapes by setting disabled attribute to false.

Save the above code as dropdownexample.html and open it in any browser, an output as below will be displayed:

Dropdown Example

Figure 1: Dropdown Example

Execution

When we run the example, following things happen:

  • HTML document is loaded into the browser and evaluated by the browser. The jQuery library is loaded and script is ready to execute the specified tasks given by the user.
  • Next, we will see the drop down list with available options. We will get several buttons for displaying a selected value, selecting different values, enabling and disabling of values.
  • We can set different values and display the selected value by using the specified buttons. We can also enable or disable the values.

slideToggle Example

This section explains how to toggles elements up and down by using slideToggle () method in jQuery. The slideToggle () method displays or hides the matched elements in the document. When we click on the toggle button; it will show the collapsible content and when we click the same button again, it hides the content. The important point we should remember is, we need to set display as none (display: none) in the CSS style sheet; otherwise the specified content will display directly on the page.

The slideToggle() has following syntax:

$(selector).slideToggle ()

Example

Let us create a example using slideToggle() method:

Listing 2: slidetoggleexample.html

<!doctype html>
<head>
<title>JQuery slideToggle</title>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
<h2>jQuery slideToggle Example</h2>
<style>
div
{
color:red;
font-family: arial;
display:none;
}
</style>
<script type="text/javascript">
   $(document).ready(function(){
      $("button").click(function(){
         $(".MyVal").slideToggle();
      });
   });
</script>
<body>
   <button>Toggle Up and down</button>
   <div class="MyVal">
      <p>Hello world!!!!</p>
      <p>Welcome to Mrbool.</p>
   </div>
</body>
</html>

The details of the above code as below:

  • We have used the code inside $(document).ready which is an event which fires up when document is ready. It will run once the page document object model is ready for JavaScript code to execute.
  • The ready function contains following code which is used for toggling the button.
$("button").click(function(){
         $(".MyVal").slideToggle();
 });

This code uses click function. Whenever the user clicks on the button to toggle the content, The slideToggle() method toggles the content up and down by using the class selector which is defined within the div element. If elements have been down, slideToggle() method will slide them up and If elements have been up, slideToggle() method will slide them down.

Save the above code as slidetoggleexample.html and open it in any browser, an output as below will be displayed:

slideToggle Example

Figure 2: slideToggle Example

Now click on the Toggle Up and down, you will see the text is shown as below:

slideToggle Example

Figure 3: slideToggle Example

Execution

When we run the example, the following things happen:

  • HTML document is loaded into the browser and evaluated by the browser. The jQuery library is loaded and script is ready to execute.
  • A button Toggle Up and down will get displayed. It shows the collapsible content when clicked on it and hides the content, when we click the same button again.

  • ajaxError Event

    This section explains the usage of ajaxError() method in jQuery. The ajaxError() is the jQuery Ajax event which specifies the function to be executed when Ajax request fails to complete or completes with an error. This event calls a handler when Ajax produces an error with the Ajax requests. When error occurs with Ajax requests, all handlers that are attached with ajaxError() method are executed this time. According to jQuery 1.8, the ajaxError() event should be attached only to the document.

    The ajaxError() event has following syntax:

    $(selector).ajaxError ([callback])
    

    Example

    The following example demonstrates usage of ajaxError() event:

    Listing 3: ajaxErrorexample.html

    <!doctype html>
    <head>
    <title>JQuery ajaxError Event</title>
    <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
    </head>
    <h2>JQuery ajaxError Event Example</h2>
    <script type="text/javascript">
       $(document).ready(function(){
    	 $("button").click(function(){
    		$("#myval").load("myfile.txt");
       	});
    	$(document).ajaxError(function(){
    		alert("Error in loading the file!!!");
    	});
       });
    </script>
    <body>
    <div id="myval" style="color:green">Click on the button to see error message</p>
    <button>Click Here</button>
    </body>
    </html>
    

    The details of the above code as below:

    • We have used the code inside $(document).ready which is an event that fires up when the document is ready. It will run once the page document object model is ready for JavaScript code to execute.
    • The ready function contains the following script, which is used for displaying ajax error message.
    $("button").click(function(){
    		$("#myval").load("myfile.txt");
       	});
    
    	$(document).ajaxError(function(){
    		alert("Error in loading the file!!!");
    	});
    

    Whenever a user clicks on the button (click here) the function $("button").click(function() is invoked and tries to load the specified file “myfile.txt”. When this request completes with an error or else fails to load the file, then it activates the ajaxError() event and displays the error message using alert box.

    Save the above code as ajaxErrorexample.html and open it in any browser, an output as below will be displayed:

    ajaxErrorEvent Example

    Figure 4: ajaxErrorEvent Example

    Execution

    When we run the example, the following things happen:

    • HTML document is loaded into the browser and evaluated by the browser. The jQuery library is loaded and script is ready to execute.
    • A button will appear after loading the document. If it fails to load the specified file, then it displays the error message using alert box.

    Setting Icon in Dropdown List Box

    This section explains setting an icon in the drop down list box using jQuery. The example which we are using below sets icon for particular values in the drop down menu list. We have categorized the lists in two groups within select element.

    We will be setting an icon of orange colored dot circle (fa-dot-circle-o), only to those elements which have attribute data-active=0.

    To achieve this we are using the select2.js which is a jQuery based replacement for select boxes. This JS gives some added functionality and makes select boxes more users friendly.

    Example

    Let’s see the example how to set the icon in the dropdown list.

    Listing 4:seticonexample.html

    <html>
    <head>
    <title>JQuery-Setting Icon in the Dropdown List Box</title>
    <script	src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
    <script	src="http://ivaynberg.github.io/select2/select2-3.4.5/select2.js" type="text/javascript"></script>
    <link href="http://ivaynberg.github.io/select2/select2-3.4.5/select2.css" rel="stylesheet">
    <link href="http://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet">
    <style>
    .fa-dot-circle-o {
        float: right;
        line-height: 25px;
        color:orange;
    }
    </style>
    </head>
    <body>
    <h2>Setting icon in Dropdown List</h2>
    <select id="Demo_Icon">
        <optgroup label="First Group">
            <option value="0" data-active="0">Hello!!!</option>
            <option value="1" data-active="1">India</option>
            <option value="2" data-active="0">New Zealand</option>
        </optgroup>
        <optgroup label="Second Group">
            <option value="2" data-active="0">England</option>
            <option value="3" data-active="1">Srilanka</option>
            <option value="3" data-active="0">West Indies</option>
        </optgroup>
    </select>
     <script>
    $("#Demo_Icon").select2({
        width: "50%",
        formatResult: function (state) {
            if (!state.id) return state.text;
    
            if ($(state.element).data('active') == "0") {
                return state.text + "<i class='fa fa-dot-circle-o'></i>";
            } else {
                return state.text;
            }
        },
        formatSelection: function (state) {
            if ($(state.element).data('active') == "0") {
                return state.text + "<i class='fa fa-dot-circle-o'></i>";
            } else {
                return state.text;
            }
        }
    });
    </script>
    </body>
    </html>
    

    The details of the above code as below:

    • We have included the jQuery library along with select2 library from following CDN’s in the HTML page, which are declared inside the head section:
    <head>
    <script	src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
    <script	src="http://ivaynberg.github.io/select2/select2-3.4.5/select2.js" type="text/javascript"></script>
    <link href="http://ivaynberg.github.io/select2/select2-3.4.5/select2.css" rel="stylesheet">
    <link href="http://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet">
    </head>
    
    • The … is a drop down list which contains two groups. Each element in this drop down list has data-active element and value attributes set.
    • The below script contains logic for setting icon in the dropdown list:
    $("#Demo_Icon").select2({
        width: "50%",
        formatResult: function (state) {
            if (!state.id) return state.text;
    
            if ($(state.element).data('active') == "0") {
                return state.text + "<i class='fa fa-dot-circle-o'></i>";
            } else {
                return state.text;
            }
        }
    
    • The code contains formatResult option. This option formats the item for display in the input box once it is selected. When option is set to zero, then the matched element will display with dot circle icon with orange color (using the class “fa fa-dot-circle-o”). This class contains CSS styles for displaying the elements in the dropdown list box.

    Save the above code as seticonexample.html and open it in any browser, an output as below will be displayed:

     Drop down list

    Figure 5: Drop down list

    Execution

    When we run the example, following things happen:

    • HTML document is loaded into the browser and evaluated by the browser. The jQuery library is loaded and script is ready to execute.
    • Next, we will get dropdown list with available options.
    • The options which have “data-active=0” will get displayed with dot circle icon with orange color.

    Scrolling a HTML Page

    This section explains scrolling of HTML page to the given anchor tag using jQuery. It shows creating scrolling functionality to the top or bottom of web page using jQuery. The below example shows two links; the first link is called Go to Bottom at the top of the page and another link called Go to Top at the bottom of the page. Both links will allow us to scroll either the top or bottom of the web page.

    Example

    Let’s consider the example for scrolling of a web page.

    Listing 5: scrollingpageexample.html

    <!doctype html>
    <head>
    <title>JQuery Scrolling HTML Page</title>
    <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
    </head>
    <h2>Scrolling of HTML Page</h2>
    <style>
    #mydiv
    {
    background-color:cyan;
    }
    </style>
    <script type="text/javascript">
       $(document).ready(function(){
          $("a.scrollToBottom").click(function(){
             $("html,body").animate({scrollTop:$(document).height()},400);
                return false;
          });
          $("a.scrollToTop").click(function(){
             $("html,body").animate({scrollTop:0},400);
                return false;
          });
       });
    </script>
    <body>
    <div id="mydiv"><a href="#mydiv" class="scrollToBottom">Go to Bottom</a></div>
    <div style="padding-bottom:100px;">"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"</div>
    <div style="padding-bottom:100px;">At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat</div>
    <div style="padding-bottom:100px;">"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"</div>
    <div style="padding-bottom:100px;">At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat</div>
    <div id="mydiv"><a href="#" class="scrollToTop">Go to Top</a></div>
    </body>
    </html>
    

    The details of the above code as below:

    • We have used the code inside $(document).ready which is an event which fires up when document is ready. It will run once the page document object model is ready for JavaScript code to execute.
    • The ready function contains below code for scrolling a webpage:
    $("html,body").animate({scrollTop:$(document).height()},400);
                return false;
          });
    
          $("a.scrollToTop").click(function(){
             $("html,body").animate({scrollTop:0},400);
                return false;
          });
    

    The code contains animate() method which allows to create animation effects on CSS properties and changes element from one state to another with CSS styles. The scrollTop() method returns vertical scrollbar position for every matched element and it is set to 0 which represents the scroll bar is at the top position and 400ms represents the speed at which the animation will run at.

    • The body tag contains the contents in which we will scroll from the top to bottom and bottom to top on the webpage.

    Save the above code as scrollingpageexample.html and open it in any browser, an output as below will be displayed:

    Scrolling HTML Page Example 1

    Figure 6: Scrolling HTML Page Example 1

    Scrolling HTML Page Example 2

    Figure 7: Scrolling HTML Page Example 2

    Execution

    When we run the example, following things happen:

    • HTML document is loaded into the browser and evaluated by the browser. The jQuery library is loaded and script is ready to execute.
    • Next, we will get two links; first link is “Go to Bottom” which goes to bottom of the page after clicking on that and second link “Go to Top” which moves top of the page when we click on that link.

    Conclusion

    In this article I've tried to cover few examples using Jquery functionality. Hope you liked the article.



I''m a full stack developer with around 10+ yrs of experience. I enjoy writing technical articles on upcoming technical trends.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login