JavaBeat

  • Home
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Privacy

Refreshing DIV Content with jQuery

January 9, 2013 by Ganesh Prakhya Leave a Comment

Frequently we may have to add or update content of the HTML elements in the web pages. The data we need to add or edit may come from various sources dynamically. jQuery has number of utility methods to achieve this goal. We can add elements or edit element’s data using jQuery.  For instance, we can update the contents of the DIV tag using jQuery’s text(),html() or load() methods.

text() Method

The jQuery’s text() method is used to get the text contents of the selected element. The element to get the text content can be selected using the selector syntax. The following snippet of code gets the contents of the DIV tag.

also read:

  • Introduction to jQuery
  • What is jQuery Ajax?

If you are looking for a good book on jQuery, please buy jQuery in Action

Here is the DIV tag.

[java]
<div id="myDiv">
<p>This is the content of the DIV tag myDiv</p>
</div>
[/java]

The jQuery code to get the DIV tag’s content.

[java]
$("#myDiv").text()
[/java]

We can also use text() method to set the contents of any element. In this case, we need to provide the new content as an argument to the text() method. The following snippet of code updates the DIV myDiv with new text.

[java]
$("#myDiv").text(‘<b>myDiv After Update</b>’);
[/java]

Optionally, we can also have a function which can return the new content being set and also have access to index and old content being replaced. The following is the example of the text() method with function usage.

[java]
$("#myDiv").text(function(index, currentContent) {
alert(index + ‘   ‘ + currentContent);
return "myDiv After Update";
});
[/java]

The parameters index specifies the index position of the element and currentContent specifies the current content of the element. The current content will be replaced with new content.

When used text() method to return the contents of an element, the HTML markup in the content will be removed and text part only will be returned.

html() Method

The jQuery’s html() method gets the HTML contents of the selected element. The element to get the HTML content can be selected using standard selector syntax.  The following code snippet updates the DIV myDiv’s HTML content with new HTML tags.

[java]
$("#myDiv").html(‘<h1>myDiv After Update</h1>’);
[/java]

Just like text() method with function we can also have html() method with function as shown in the below example:

[java]
$("#myDiv").html(function(index, currentContent) {
alert(index + ‘  ‘ + currentContent);
return "myDiv After Update";
});
[/java]

When used html() method to return the contents of an element, the HTML markup in the content will be returned.

load() Method

We can also use load() method to update the selected element’s content. This is particularly useful if the content to be updated is residing externally and accessible via URL. The example code retrieves content from externally located welcome.htm and updates the DIV myDiv.

[java]
$("#myDiv").load(‘welcome.html’);
[/java]

These are the possible ways jQuery can refresh the element content.

also read:

  • Introduction to jQuery
  • What is jQuery Ajax?

If you are looking for a good book on jQuery, please buy jQuery in Action

Filed Under: jQuery Tagged With: jQuery

jQuery Ajax Introduction

January 6, 2013 by Ganesh Prakhya Leave a Comment

As we already know, AJAX is a technique to update parts of a web page without reloading the entire web page. Ajax stands for Asynchronous JavaScript and Xml. jQuery supports AJAX functionality through various methods. Using jQuery AJAX methods we can request text, HTML, XML or JSON content from the server. We can send HTTP Get and HTTP Post requests using jQuery AJAX methods and also display the external data in the web page by loading the external data into the selected HTML elements.

also read:

  • Introduction to jQuery
  • jQuery Selectors : ID selector, Class selector and Element selector

If you are looking for a good book on jQuery, please buy jQuery in Action

We can have AJAX functionality without using the jQuery but we’ll have to handle browser compatibility issues on our own because each browser has different AJAX syntax and implementation. jQuery eliminates this problem by providing unified AJAX methods. This is one of the greatest advantages of using the frameworks which handles the problems of providing the browser compatibility, etc.

load() Method

The load() method loads data from remote server and puts the loaded data into the selected HTML element of the page. This method has three parameters, the following table summarizes the parameters.

URL The URL of the data to load.
data (Optional) request parameters. These are key/value   pairs we can send along with URL as part of the query string.
callback (Optional) function to execute after the load()   method completes execution. We specify the name of the function to execute.

The following code snippet loads the content from welcome.html file and displays it into the myDiv.

[java]
$(document).ready(function(){
$("#myDiv").load("welcome.html");
});
[/java]

We can also have optional callback method to execute after the load method executes successfully. The following code snippet loads the content from welcome.html just like above example and also has a callback function defined.

[java]
$(document).ready(function(){
$("#myDiv").load("welcome.html", function(response,statusCode, requestObj){
alert(response + ‘  ‘ + statusCode + ‘  ‘ + requestObj);
});
});
[/java]

Notice that the callback function in the above example has three parameters which represent the response from the load method call if load method call is succeeded, the status code of the call and XMLHTTPRequest object respectively. The sample run of the above code gives us the following output as shown in the screen capture.

ajax-callback

We can find out whether the call is successful by checking the parameter statusCode. For successful call the statusCode will be success whereas for failed call the statusCode will be error.

In case of error we can use requestObj.status and requestObj.statusText to find out the status of the failed request and reason for failure. The following is the sample code and output of a sample run with an invalid URL to load.

[java]
$(document).ready(function(){
$("#myDiv").load("welcomeNotFound.html", function(response,statusCode, requestObj){
alert(statusCode + ‘  ‘ + requestObj.status + ‘  ‘ + requestObj.statusText);
});
});
[/java]

ajax-callback-invalid

Thus we can have alternate functionality in case the requested URL is failed to load.

$.get() Method

The $.get() method sends a HTTP Get request to the specified URL and gets response back. The following snippet of jQuery code sends a GET request to the page welcome.html and prints the data and status using the alert box.

[java]
$(document).ready(function(){
$("#btn").click(function(){
$.get("welcome.html",function(data,status){
alert("Data: " + data + "\nStatus: " + status);
});
});
});
[/java]

We can also send some data along with the request optionally as shown below:

[java]
$.get("welcome.php", { username:"Some User", usertype:"Subscribed User" });
[/java]

The following example also sends the GET request with some data and processes the response returned from the server.

[java]
$(document).ready(function(){
$("#btn").click(function(){
$.get("welcome.php",{username: "Some User", usertype: "Subscribed User"},
function(data, status){
alert("Data: " + data + "\nStatus: " + status);
});
});
});
[/java]

$.post() Method

The $.POST sends a HTTP Post request and gets response back from the server. The following snippet of jQuery code sends a POST request and appends the result to the div myDiv.

[java]
$("#btn").click(function() {
$.post("post_data.php", {dataToPost: "myData"},function(result){
$("#myDiv").html(result);
});
});
[/java]

Optionally, we can also specify dataType when sending a POST request. The dataType indicates the type of the data expected from the server response. jQuery will do a guess if we do not specify the dataType. The possible types are html, xml, JSON and text etc.

I hope this article would have provided the very basis idea on using the jQuery Ajax in your project. In my next posts I will write about various examples using the jQuery Ajax. If you want to receive the mail updates, please subscribe here.

also read:

  • Introduction to jQuery
  • jQuery Selectors : ID selector, Class selector and Element selector

If you are looking for a good book on jQuery, please buy jQuery in Action

Filed Under: jQuery Tagged With: jQuery

jQuery Selectors : ID selector, Class selector and Element selector

January 2, 2013 by Ganesh Prakhya Leave a Comment

We use jQuery selectors to identify, select and manipulate the elements of the HTML document. Using jQuery selectors we can identify an element with its ID and class. Once we identify the element(s) we want, we can read the element’s attributes along with attribute values, apply style sheets, hide or show element content based on conditions and much other functionality. Please subscribe to our future articles here.

  • Buy : jQuery in Action

Fundamentally, let’s discuss about three types of jQuery selectors most commonly used.

  • ID selector
  • Class selector
  • Element selector

ID selector

The ID selector is used to identify a specific element by the element’s ID attribute. We use ID selector to particularly identify a single unique element of a page. The following example finds a div element with ID dataDiv.

[java]$("#dataDiv")[/java]

Once we found the div element we needed, we can make changes to the element. The following example adds a border to the div element we just found in the above example.

[java]$("#dataDiv").css("border", "5px solid green");[/java]

Class selector

The class selector is used to identify a single element or a set of elements in a page with common class attribute. We may get more than one element when we use class selectors. The following example finds an element with class dataClass.

[java]$(".dataClass")[/java]

Here is the element with its class attribute.

[java]<div class="dataClass">…</div>[/java]

In the above example, since we have only one div element with class dataClass, we only get one element. However, if we have more than one div element with same class we may get multiple elements. For instance, the following example has more than one div elements with same class and we use class selectors to get all the elements.

[java]
<div id="dataDiv1" class="dataClass">…</div>
<div id="dataDiv2" class="dataClass">…</div>
<div id="dataDiv3" class="dataClass">…</div>
<div id="dataDiv4" class="dataClass">…</div>
[/java]

The jQuery code will returns four elements.

[java]$(".dataClass")[/java]

In order to iterate over four of div elements we get, we use each construct.

[java]
$(".dataClass").each(function(index) {
alert($(this).text() + " : " + index);
});
[/java]

In the above code snippet, we are iterating over the div elements and displaying their index and contents. Notice that for each iteration in the loop, the $(this) refers to the current element. The function text() displays the contents of the element.

Element selector

We use jQuery element selectors to select elements based on their tag names. The following example gets all heading 1 tags (H1).

[java]
$("h1")
[/java]

Once we have the elements we can manipulate them. The following example hides all the heading 1 tags.

[java]
$("h1").hide();
[/java]

jQuery selectors are flexible, programmer friendly and great way to locate elements in the HTML pages. We can use jQuery selectors for formatting, hiding or showing content conditionally, appending the element to another element and much more.

  • Buy : jQuery in Action

Filed Under: jQuery Tagged With: jQuery

Introduction to jQuery

December 28, 2012 by Ganesh Prakhya Leave a Comment

jQuery is a free, open source JavaScript library intended to simplify multi-browser client side scripting. jQuery has very active developer community constantly improving its core and jQuery is the most famous JavaScript library as of today. The current version of jQuery is 1.8. We can use jQuery to manipulate DOM elements, send Ajax request, receive JSON response, perform animations, and develop user interface widgets and much more. jQuery also supports sophisticated event handling. Developers can extend the jQuery functionality by developing plug-ins. If you are interested in receiving future articles, please subscribe here.

  • Finding Duplicate Input Elements Using jQuery
  • jQuery in Action

jquery

Purpose of using jQuery

jQuery is a programming style. Although much functionality like JavaScript slideshow can be implemented using plain JavaScript, things will be simplified if we choose to use jQuery. Moreover, jQuery gives us flexibility to select and manipulate DOM elements. jQuery selectors (HTML selectors and CSS selectors) provides us easy way to deal with DOM elements. jQuery makes a lot of things easy instead of “re-inventing the wheel”.

How jQuery works – A First Example

Let’s start by creating a simple HTML page which displays a welcome message when the page loads.

[sourcecode language=”html”]
<html>
<head>
<script type="text/javascript" src="jquery-1.8.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
alert("Welcome to jQuery!");
});
</script>
</head>
<body>
</body>
</html>
[/sourcecode]

The above code snippet displays an alert message to the user. Note that the jQuery library is referenced from within the <head> tag. Also notice that we did not used traditional onLoad(…) event in the <body> tag to display the message after HTML page loads.  In the traditional approach (using onLoad event in the body tag) the JavaScript will not be invoked until all the images and ads in the web page are completely loaded. jQuery solves this problem by checking until document is loaded and ready for manipulation.

ready event

The ready event from the above code is one of the many jQuery events. This event makes sure that any function or handler supplied to this event gets executed after the DOM is fully loaded. Thus, in the above example, the alert message is shown only after DOM is completed loaded.

A realistic jQuery Example

In this example we will hide or show a particular content based on toggle key selection.

[sourcecode language=”html”]
<html>
<head>
<script type="text/javascript" src="jquery-1.8.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#toggle").click(function() {
var isMyDivVisible = $("#myDiv").css(‘display’);
if (isMyDivVisible == ‘block’) {
$("#myDiv").hide();
$("#toggle").attr(‘value’, ‘Show’);
} else {
$("#myDiv").show();
$("#toggle").attr(‘value’, ‘Hide’);
}
});
});
</script>
</head>
<body>
<div id="myDiv">
<p>This is myDiv</p>
</div>
<input id="toggle" type="button" value="Hide"/>
</body>
</html>
[/sourcecode]

In the above example we have one HTML div tag with id of myDiv and a simple button with id of toggle and default value of ‘Hide’. Upon clicking the button we’re hiding the div myDiv and at the same time we’re changing the button’s value to ‘Show’. Clicking again the button will eventually shows the myDiv content and also button’s value changed to ‘Hide’. To achieve this functionality we’re doing several things as outlined below for clarity.

  • We’re binding click event to the button toggle.
  • In the click event (or when user clicks the button) we’re retrieving the CSS display property of myDiv. Essentially, the  display property controls the visibility of an HTML element.
  • Based on the display property whether its block or none we’re hiding or showing the myDiv respectively. At the same time we’re also updating button’s value for better usability.

This simple example demonstrates the power of jQuery and the control it has over DOM tree and its full fledged event handling mechanism.

jQuery Resources

  • The official jQuery website is http://jquery.com/
  • Latest version of jQuery can be downloaded from http://jquery.com/download/
  • jQuery documentation can be referred from http://api.jquery.com/

Filed Under: jQuery Tagged With: jQuery

  • « Previous Page
  • 1
  • 2

Follow Us

  • Facebook
  • Pinterest

As a participant in the Amazon Services LLC Associates Program, this site may earn from qualifying purchases. We may also earn commissions on purchases from other retail websites.

JavaBeat

FEATURED TUTORIALS

Answered: Using Java to Convert Int to String

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Copyright © by JavaBeat · All rights reserved