Monday, 29 April 2013

How to generate dynamic row and delete that row using add and delete button using jQuery

Hi friends. I am sharing with you that how to generate dynamic row and also delete that dynamic generated row this concept is used when u will developed billing software because in billing software we do not know how many item purchase by customer. So base on customer item we need to generate row or this can be used in the storing contact details of person. Here I giving example for storing contact details of person

For This example we need to include the jQuery.js file.

This GenerateRow.html  file which is generated row and delete row.


 <html>  
 <head>  
 <script src="jquery.js"></script>  
 <script>  
 var k;  
 $(document).ready(function()  
 {  
      k=1;     //for first row  
      $("#rdata").append(showData());  
      $("#add").live('click',function()  
     {  
               k++;        
       $('#rdata').append(showData());  
                $("#counter").val(k);      
     });  
 });  
 function lremove(l)  
 {  
            var lid=l.id;  
            var rowno = lid.match(/\d+$/);  
            if(rowno>1)  //if only one row then i am now allow to remove.if more than then remove that row
             {  
                 $("#line"+rowno).remove();  
             }  
 }  
 function showData()  
 {       
           var str="<table><tr id='line"+k+"'>"  
                     +"<td align='center' width='20'>"  
                          +"<font face='calibri' size='2' color='#'><b>"+k+")</b></font>"  
                     +"</td>"  
                     +"<td align='center' width='150'>"  
                     +"<input type='text' name='name"+k+"' id='name"+k+"' >"  
                     +"</td>"  
                  +"<td align='center' width='80'>"  
                          +"<input type='text' name='number"+k+"' id='number"+k+"' value=''>"  
               +"</td>"  
                  +"<td align='center'>"  
               +"<input type='button' id='add' value='+' height='15' width='15'/></td>"  
                     +"<td><input type='button' value='x' id='remove"+k+"' onclick='lremove(this)' src='Delete.png' height='30' width='30'/></td>"  
                +"</tr></table>";  
       return str;  
 }  
 </script>  
 </head>  
 <body>  
 <table>  
 <caption>Storing Mobile Number</catption>  
 <tr>  
      <td width='70'></td>  
      <td width='140' align='left'>Name</td>  
      <td width='150' align='left'>Mobile Number</td>  
 </tr>  
 </table>  
 <form name="frminfom" action="ConnectRowGenerate.jsp">  
      <div id="rdata">  
      </div>  
      <input type="hidden" value="1" name="counter" id="counter">  
      <input type="submit" value="submit">  
      <input type="reset" value="clear">  
 </form> 
  </body>  
 </html>  

in this above example i used the

$(document).ready(function()
{
   
    code
});
this above function of jQuery which is called after document will be load or after your document will be ready.
inside this i am writing following code.

k=1;   
$("#rdata").append(showData());

k-> variable i used for giving each row unique name.
rdata-> is an div id in which i need to add a row

append(showData())
this append method is used for append content at last in div(rdata).

showData() is an function which it will return the Dynamically generated row so that row i am passing as a parameter of append so its will append to rdata (div tag).
eg.append(showData()).

The ShowData function containt
str="<table><tr id='line"+k+"'>"
.....
return str;

here i used table and i am storing this table into the str variable because i need to return thats why and i assigning the unique row id
like  id='line"+k"'
so this will replace as line1 after u generated second row it will line2 as k variable will increase when you add the new row.


$("#add").live('click',function()
{
});
this function will invokes when user click on the add button
the live() is an method which is providing the fecilities for firing the on click(othere even) event on new generated add button if you will not used live then its add only one row.

Removing row
<input type='button' value='x' id='remove"+k+"' onclick='lremove(this)' src='Delete.png' height='30' width='30'/>


here when user click on remove button i am passing the 'this' object which is reffere the current row remove button object and in function
function lremove(l)
Now here  'this' is an object will replace with 'l' object name and get id from object.
var lid=l.id
now lid will store the id of remove button..e.g remove1,remove2..
var rowno = lid.match(/\d+$/);
this will extract last digits from the string.
e.g remove1 then its will return 1.

$("#line"+rowno).remove();
here line is common when you generating row its one row value containt line1,line2.
so line will same just i need to contacate the number of line and  remove() method is used for remove the specific tag.

How to Read values using jsp file ConnectRowGenerate.jsp when user click on submit button.
code.
 <%  
 int counter=Integer.parseInt(request.getParameter("counter"));  
 for(int i=1;i<=counter;i++)  
 {  
       try  
       {  
        String name=request.getParameter("name"+i);  
        String number=request.getParameter("number"+i);  
    out.println(name + " "+number+"<br>");  
   }  
   catch(Exception e)  
   {  
           continue;  
      }  
 }  
 %>  


Now we will understand above code
counter variable which containt thea number of row add in page.

try and catch block as if user will removed line from middle and we try to read that value which is not available then it will throw exception so for that i am writing code in try and catch block and if it will throw error then its will go in catch block and again its will continue reading with next row or line.

output:
when you open GenerateRow.html its will show like following.




if you click on add button it will add new row.

if you click on delete button it will remove row but here first row its not remove as i am gave validation so now when u click on submit its will call the ConnectRowGenerate.jsp file and its will display the data.
 
You can download above example from  here

Saturday, 27 April 2013

how to read an XML file via DOM XML parser in java

The XML is very simple language that allows the developers to store the structured data into XML files.XML is designed to transport and store data.

XML Document Example
In this tutorial, we will show you how to read an XML file via DOM XML parser. DOM parser parses the entire XML document and loads it into memory; then models it in a “TREE” structure for easy traversal or manipulation.
In short, it turns a XML file into DOM or Tree structure, and you have to traverse a node by node to get what you want.

e.g of your  personalinfo.xml file

 <?xml version="1.0"?>  
 <company>  
      <staff id="1">  
           <firstname>ishwar</firstname>  
           <lastname>Panjari</lastname>  
           <nickname>ish</nickname>  
           <salary>1000</salary>  
      </staff>  
      <staff id="2">  
           <firstname>jaydip</firstname>  
           <lastname>Raol</lastname>  
           <nickname>DK</nickname>  
           <salary>2000</salary>  
      </staff>  
 </company>  

when you create xml file you need to specify the version of xml file.  i created <company>---</company> this is called as root element of xml file.other its called node.eg. staff.

 import javax.xml.parsers.DocumentBuilderFactory;  
 import javax.xml.parsers.DocumentBuilder;  
 import org.w3c.dom.Document;  
 import org.w3c.dom.NodeList;  
 import org.w3c.dom.Node;  
 import org.w3c.dom.Element;  
 import java.io.File;  
 public class ReadXMLFile {  
  public static void main(String argv[]) {  
   try {  
      File fXmlFile = new File("personalInfo.xml");//personalInfo.xml is xml file name  
      DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();  
      DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();  
      Document doc = dBuilder.parse(fXmlFile);  
      System.out.println("Root element :" + doc.getDocumentElement().getNodeName());  
      NodeList nList = doc.getElementsByTagName("emp");//here emp is the tag in xml file  
      System.out.println("----------------------------");  
      for (int temp = 0; temp < nList.getLength(); temp++) {  
           Node nNode = nList.item(temp);  
           System.out.println("\nCurrent Element :" + nNode.getNodeName());  
           if (nNode.getNodeType() == Node.ELEMENT_NODE) {  
                Element eElement = (Element) nNode;  
                System.out.println("Staff id : " + eElement.getAttribute("id"));  
                System.out.println("First Name : " + eElement.getElementsByTagName("firstname").item(0).getTextContent());  
                System.out.println("Last Name : " + eElement.getElementsByTagName("lastname").item(0).getTextContent());  
                System.out.println("Nick Name : " + eElement.getElementsByTagName("nickname").item(0).getTextContent());  
                System.out.println("Salary : " + eElement.getElementsByTagName("salary").item(0).getTextContent());  
           }  
      }  
   } catch (Exception e) {  
      e.printStackTrace();  
   }  
  }  
 }  

here we used the classes
DocumentBuilderFactory:Defines a factory API that enables applications to obtain a parser that produces DOM object trees from XML documents.

DocumentBuilder:Defines the API to obtain DOM Document instances from an XML document. Using this class, an application programmer can obtain a Document from XML.

An instance of this class can be obtained from the DocumentBuilderFactory.newDocumentBuilder() method. Once an instance of this class is obtained, XML can be parsed from a variety of input sources. These input sources are InputStreams, Files, URLs, and SAX InputSources.


output:

Root element :company
----------------------------
Current Element :emp
Staff id : 1
First Name : ishwar
Last Name : Panjari
Nick Name : ish
Salary : 1000

Current Element :emp
Staff id : 2
First Name : jaydip
Last Name : Raol
Nick Name : DK
Salary : 2000

Friday, 5 April 2013

How to read Multiple checkbox value and Radio button value at client side and serverside using jsp


Html file

 <html>  
 <head>  
 <title>Check Box Example</title>  
 <script src="jquery.js"></script>  
 <script>  
 function checkdisp()  
 {  
       $('input[name="hobby"]:checked').each(function()  
       {  
      alert("Check Button Value:"+$(this).val());  
    });  
      alert("The Radio Button Value:"+$('input[name="gen"]:checked').val());  
 }  
 </script>  
 </head>  
 <body>  
 <form name="frmpdf" action="connectCheck.jsp" method="GET">  
 Hobbies:<br>  
            <input type="checkbox" name="hobby" value="Cricket">Cricket<br>  
            <input type="checkbox" name="hobby" value="Movie">Watching Movie<br>  
            <input type="checkbox" name="hobby" value="Book">Reading Book<br>  
            <br>  
 Gender:<input type="radio" value="Male" name="gen" Checked>Male  
           <input type="radio" value="Female" name="gen">Female  
           <br>  
            <input type="button" value="ClientSide" onclick="checkdisp()">  
            <input type="submit" value="ServerSide">  
 </form>  
 </body>  
 </html>  


jsp file
connectCheck.jsp
 <%  
      out.println("CheckBox Value");  
      String[] checkb=request.getParameterValues("hobby");  
      try  
      {  
           for(int i=0;i<checkb.length;i++)  
                out.println(checkb[i]);  
           out.println("Radio Button value");  
           String radiob=request.getParameter("gen");  
           out.println(radiob);  
      }  
      catch(Exception e)  
      {  
           out.println("erro "+e.toString());  
      }  
 %>  

Client side : when you click on clientSide button it will display value of selected Checkbox and Radio button in Html File using jquery.

Server side:after selecting value in html page when you click on servierSide button it  will got to connectCheck.jsp page that print the selected checkbox and Radio button value.
           i used try and catch block because if user is not selected checkbox value and you try to access then its will throw error so handling exceptin i used try and catch block.