Search Web

Custom Search

Tuesday, September 13, 2011

Conditional validation with jQuery

While designing HTML form where decision made between validate a field or not is based on the value of other field, you can easily write a custom validation handler  function which can decide whether a field require validation or not.

For example see following picture in which passport number require validation only if user have a valid passport.















Here is jQuery handler function which validate passport number fileld based on radio button value.

$(function(){
    jQuery.validator.addMethod("custom",
        function(value, element) {
            if($('input[name=valid_passport]:checked').val()=='yes' && value.length<=0){
                 return false;
            }else{
                 return true;
            } return true;
    }, "Require field" );

    $("#myform").validate();
 });

Complete demo page can be found here


Monday, May 30, 2011

Excel to HTML table conversionee

You can always save your MS Excel sheets to html by selecting "Save As" from main menu but after conversion look at the HTML code generated by Excel. This code is near to "unreadable" by humans. And if  you want to style the table generated by Excel it is very hard to do.

Now copy your cells in Excel sheet and paste them  into some text editor like notepad in Windows. You will examine that cells and rows are separated by tab and new line respectively.

 To get clean HTML code we can use this information, all you have to do is

  1. Split each line by tab character and encapsulate each chunk into <td></td>
  2. Encapsulate each line into <tr></tr> tag
  3. Now encapsulate whole text into <table></table> tag

This will give you neat and cleaner HTML code of table.

For automating this process, I wrote a simple javascript function and created a HTML page that utilizes it. Complete code of function and HTML page are in same file.

Additionally it uses jQuery for event handling and  dynamic preview and code update.

Code of HTML page is as follows:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>M.S. Excel to HTML table converter</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.5.1.min.js"></script>

<script type="text/javascript">
function trim(stringToTrim) {
return stringToTrim.replace(/^\s+|\s+$/g,"");
}

$(document).ready(function(){
$("#generate").click(function(){
var text = $("#text").val();

var txtSplit = text.split("\n");

var genhtml = "";
var genprv = "";
var tab = "&nbsp;&nbsp;&nbsp;&nbsp;";

var tag_table_start = '&lt;table&gt;';
var tag_tr_start = '&lt;tr&gt;';
var tag_td_start = '&lt;td&gt;';

if(trim($("#tableclass").val()).length == 0){
tag_table_start = '&lt;table&gt;';
}else{
tag_table_start = '&lt;table class="'+trim($("#tableclass").val())+'"&gt;';
}

if(trim($("#trclass").val()).length == 0){
tag_tr_start = '&lt;tr&gt;';
}else{
tag_tr_start = '&lt;tr class="'+trim($("#trclass").val())+'"&gt;';
}

if(trim($("#tdclass").val()).length == 0){
tag_td_start = '&lt;td&gt;';
}else{
tag_td_start = '&lt;td class="'+trim($("#tdclass").val())+'"&gt;';
}


for(var i=0;i<txtSplit.length;i++){

var cellSplit = txtSplit[i].split("\t");

var genline = "";
for(var j=0;j<cellSplit.length;j++) {
cellSplit[j]=cellSplit[j].replace("<","&lt;");
cellSplit[j]=cellSplit[j].replace(">","&gt;");
genline = genline + tab + tab + tag_td_start + cellSplit[j] + "&lt;/td&gt"+"<br>";
}
genhtml = genhtml + tab  + tag_tr_start + "<br>" + genline + tab + "&lt;/tr&gt;"+"<br>";

}
var result_code = tag_table_start+'<br/>'+genhtml+"&lt;/table&gt;<br/>";
$("#result").html(result_code);


for(var i=0;i<txtSplit.length;i++){

var cellSplit = txtSplit[i].split("\t");

var genline = "";
for(var j=0;j<cellSplit.length;j++) {
genline = genline + "<td>" + cellSplit[j] + "</td>";
}
genprv = genprv + "<tr>" + genline + "</tr>";

}

genprv = "<table border=\"1\">" + genprv + "</table>";


$("#preview").html(genprv);

});
});

</script>

</head>
<body>
<p><b>Developed by:</b> Deepesh Goud <b>Blog:</b>&nbsp;<a href="http://javahackz.blogspot.com">http://javahackz.blogspot.com</a></p>
<h2>M.S. Excel to HTML table converter</h2>
<p>Paste your cells from Excel or other spreadsheet here:</p>
<form>
<textarea rows="15" cols="100" id="text"></textarea>
<br/>
&lt;TABLE&gt; class :<input type="text" id="tableclass">&nbsp;&nbsp;
&lt;TR&gt; class :<input type="text" id="trclass">&nbsp;&nbsp;
&lt;TD&gt; class :<input type="text" id="tdclass">&nbsp;&nbsp;
<input type="button" value="Generate" id="generate">
</form>
<br/><br/>
<p>Preview:</p>
<div id="preview"></div>
<br/><br/>
<p>HTML Table Code :</p>
<div id="result" style="background:#e5eecc;">
</div>
</body>
</html>


Offline version including jQuery library can be downloaded from here.  Just unzip excel_to_html.zip and open excel_to_html.html file in your favorite web browser. For usages, just copy cells from any spreadsheet application like MS Excel and paste them into text area and press "generate html" button.

Online demo of Excel to HTML table


Thursday, May 26, 2011

Dynamic table in html form using jQuery and posting data using JSON



1. Introduction

In various situations number of rows in a data table in html form are not fixed for example if you are working on inventory management application and designing a goods receipt note (GRN) form the number of rows in goods list in form is not fixed and varies according to types of goods received.

The classical approach of implementation requires multiple submission of form for each new row inserted and further you have to maintain the state of form in session or hidden fields inside the form it self. Of course, it puts lots of load on server and network resources but with the help of jQuery ( a java script library)  you can design a form in such a way that you can add multiple rows to a dynamic table without form submission and send all data to back end application on final submission.

2. Sample Application


Following is the image of sample web application "GRNApp".


















(Fig.1 Main application view)














(Fig.2 Result after submit form)


The functioning of application is as follows

1. The add button adds a new row to a table and data is ultimately stored in a two dimensional array object.
2. The submit button serialize this array object to JSON and finally submit the form to back end application which is a servlet.
3. Finally servlet deserialize the JSON string received as parameter to two dimensional table implemented using a List.

If you have never used JSON before, read more about it from here http://www.json.org/

The structure GRNApp application is as follows
















On click of add button on the form in addform.html. following jQuery function is called


$(".addbutton").click(function() {
var row = new Array(4);
row[0] = $("#txtbox1").val();
row[1] = $("#txtbox2").val();
row[2] = $("#txtbox3").val();
row[3] = $("#txtbox4").val();

data.push(row);

refresh();
});



It simply adds an array object containing text box values to a global array object "data" and refreshes the table by calling refresh() function.

The first column in dynamic table is S.No which is simply index +1 position of row in global array object "data". This S.No. also act as row ID to identify unique row in table for deleting single row. Let's see how it is done

Look at the code of delete button in addform.html for dynamically added row

var abutton = $('<input type="button" class="deleterow" value="Delete">');

When this button with css class "deleterow" against any dynamically added row is clicked, following function is called. It try to detect the current row i.e. <TR> in wich this button is located and finds its first child which is first <TD> containing S.No which is served as row ID.

$(".deleterow").live("click",function(){
var val = $(this).parents("tr:first").children(":nth-child(1)").text();
data.splice(val-1,1);
refresh();
});


The live() function is required to achieve this because contents of table are dynamically added to the DOM.

Up on submission of form submit event is triggered and handler function is called.

$("#myform").submit(function(){
var val = $.toJSON(data);
$("#data").attr("value",val);

if(data.length == 0){
alert("Table is empty !");
return false;
}else{
return true;
}
});

This submit handler function converts the contents of two dimensional global array "data" to JSON string and sets the value of hidden parameter named "data" inside the form. It also check the empty table and popup the error if it is empty.

The complete code of grnform.html is as follows

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>GRN Sample Application</title>

<link type="text/css" href="styles.css" rel="stylesheet" />
<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="jquery.json-2.2.min.js"></script>

<script type="text/javascript">

data = new Array();

$(document).ready(function(){
$(".addbutton").click(function() {
var row = new Array(4);
row[0] = $("#txtbox1").val();
row[1] = $("#txtbox2").val();
row[2] = $("#txtbox3").val();
row[3] = $("#txtbox4").val();

data.push(row);

refresh();

});

$(".clearbutton").click(function(){
clearall();
});


$(".deleterow").live("click",function(){
var val = $(this).parents("tr:first").children(":nth-child(1)").text();
data.splice(val-1,1);
refresh();
});

$("#myform").submit(function(){
var val = $.toJSON(data);
$("#data").attr("value",val);

if(data.length == 0){
alert("Table is empty !");
return false;
}else{
return true;
}
});


});

function clearall(){
data = [];
$("#datatable").find("tr:gt(1)").remove();
publishtable();
}

function refresh(){
$("#datatable").find("tr:gt(1)").remove();
publishtable();
}

function publishtable(){
for(var c=0;c<data.length;c++){

var trow = $('<tr valign="middle">').addClass("contact");
$("<td>").text(c+1).appendTo(trow);

for(var i=0;i<4;i++){
$("<td>").text(data[c][i]).appendTo(trow);
}

var abutton = $('<input type="button" class="deleterow" value="Delete">');
var acell = $("<td>");

abutton.appendTo(acell);
acell.appendTo(trow);


$("#datatable").append(trow);
}
}
</script>
</head>
<body>
Dynamic table update and posting using jQuery and JSON
<br/><br/>
<b>Goods Receipt Note (GRN)</b>
<br/><br/>
<table border="0">
<tr>
<td>Goods Name</td>
<td>Quantity</td>
<td>Rate</td>
<td>Batch No.</td>
<td></td>
</tr>
<tr>
<td><input type="text" name="txtbox1" id="txtbox1" class="txtbox">&nbsp;&nbsp;</td>
<td><input type="text" name="txtbox2" id="txtbox2" class="txtbox">&nbsp;&nbsp;</td>
<td><input type="text" name="txtbox3" id="txtbox3" class="txtbox">&nbsp;&nbsp;</td>
<td><input type="text" name="txtbox4" id="txtbox4" class="txtbox">&nbsp;&nbsp;</td>
<td>
<input type="button" name="mybutton" class="addbutton" id="addbutton" value="Add">&nbsp;&nbsp;
<input type="button" name="clearbutton" class="clearbutton" id="clearbutton" value="Clear All">
</td>
</tr>
</table>

<br/>
<br/>
<br/><br/><br/>
<table id="datatable" class="contacts">
<thead>
<tr>
<td class="contactDept" colspan="6">Items in GRN</td>
</tr>
</thead>

<tbody>
<tr class="contact_head">
<td>S.No.</td>
<td>Goods Name</td>
<td>Quantity</td>
<td>Rate</td>
<td>Batch No.</td>
<td>Action</td>
</tr>
</tbody>
</table>
<br/>
<p>** End of table **</p>
<br/>
<br/>
<form id="myform" action="grnservlet" method="post">
<input type="hidden" id="data" name="data">
<input type="submit" name="submitbutton" class="submitbutton" id="submitbutton" value="Submit Form">
</form>


</body>
</html>

On server side form is submitted to grnservlet servlet. This servlet convert the JSON string in parameter to the JSONArray object  with the help of json-lib library

JSONArray jsobj = JSONArray.fromObject(request.getParameter("data"));

Each item in this jsobj  is also an JSONArray which represents a single row. Thus it again convert each object in jsobj to JSONArray and finally find attributes of a single row represented by object s.

for(Object i:jsobj){
JSONArray jsarray = JSONArray.fromObject(i);
.
.
for(Object s:jsarray){
.
.
.
}
}


The complete code of grnservlet.java is as follows


package myapp;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.*;

/**
 * Servlet implementation class grnservlet
 */
public class grnservlet extends HttpServlet {
private static final long serialVersionUID = 1L;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public grnservlet() {
        super();
        // TODO Auto-generated constructor stub
    }

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
JSONArray jsobj = JSONArray.fromObject(request.getParameter("data"));
ServletOutputStream os = response.getOutputStream();

os.print("<html><title>GRN Sample Application</title><body>");
os.print("<table border=\"1\">");
os.println("<tr><td>S.No.</td><td>Goods Name</td><td>Quantity</td><td>Rate</td><td>Batch No.</td></tr>");
int index = 1;
for(Object i:jsobj){
JSONArray jsarray = JSONArray.fromObject(i);
os.println("<tr>");
os.println("<td>"+index+"</td>");
for(Object s:jsarray){
os.println("<td>");
os.print(s.toString());
os.print("</td>");
}
index++;
os.print("</tr>");
}
os.print("</table>");
os.print("</body></html>");
}

}


3. Dependencies 

The grnform.html is a main view of application. It uses jQuery 1.4.2 and json plugin for jQuery. You can download them from following links

http://code.google.com/p/jquery-json/downloads/detail?name=jquery.json-2.2.min.js

http://code.jquery.com/jquery-1.4.2.min.js

Conversion of serialized JSON  string received as parameter to two dimensional list object is done using open source json-lib library which can be obtained from here

http://sourceforge.net/projects/json-lib/files/

Json-lib requires (at least) the following dependencies in your classpath:

jakarta commons-lang 2.5
jakarta commons-beanutils 1.8.0
jakarta commons-collections 3.2.1
jakarta commons-logging 1.1.1
ezmorph 1.0.6

I have included these dependencies in a separate zip file. See Conclusion section at the last of this article.

Platform and API version information of sample application is as follows:

Application server - Tomcat 5.5
Servlet version - 2.4
JDK - 1.5 (or simply jdk5)


4. Conclusion

With little help of jQuery and JSON we can design the presentation layer of web application in such a way which is both efficient and more interactive.

The Eclipse project (using Eclipse 3.6) of sample web application, dependencies and binaries for testing can be downloaded from following links

GRNApp_Source.zip
GRNApp_Dependencies.zip
GRNApp_Binary.zip (dependencies included)

For testing of application unzip the GRNApp_Binary.zip file and copy GRNApp directory to webapp directory of tomcat installation and restart it. That's it all.

Thursday, May 19, 2011

Disable text field based on radio button selection using jQuery


In may cases it is required to disable text filed in HTML form based on radio button selection. You can do this using plane java script however it far easy using jQuery. By using jQuery you don't have to worry about browser compatibly. 


All you need to do is just put follwing code in head section of HTML or JSP, PHP etc.
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>


Now add folling script after text field and radio buttons in form. Assuming class attribute of radio button is "control"  and ID attribute of text field is "txtbox". Values of radio 


buttons are "enabled" and "disabled" respectively.

<script type="text/javascript">
$(".control").change(function(){
if($(this).val()=="disable"){
$("#textbox").attr("disabled","disabled");
}else{
$("#textbox").removeAttr("disabled");
}
});
</script>

This example loads jQuery script from google api hosting. However if you prefer off line version you can download it from here

Complete working example is as follows


<html>

<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>


<body>


<form>
<input type="radio" value="enable" name="control"  class="control" checked="checked">Enable&nbsp;&nbsp;
<input type="radio" value="disable" name="control" class="control" >Disable

<br/><br/>

<input type="text" name="textbox" id="txtbox">

<script type="text/javascript">
$(".control").change(function(){
if($(this).val()=="disable"){
$("#textbox").attr("disabled","disabled");
}else{
$("#textbox").removeAttr("disabled");
}
});
</script>
</form>
</body>
</html>