Labels

.NET Job Questions About Java Absract class Abstract class Abstract Class and Interface Aggregation ajax aop apache ofbiz Apache ofbiz tutrial Association authentication autocad basics batch Binary Tree bootstrap loader in java build Builder design pattern C++ Job Questions caching CallableStatement in java certifications Chain of responsibility Design pattern charts check parentheses in a string Classes classloader in java classloading concept code quality collage level java program Composition concurrency Concurrency Tutorial Converting InputStream to String Core Java core java concept core java interview questions Core Java Interview Questions Core Java Questions core java tutorial CyclicBarrier in Java data structures database Database Job Questions datetime in c# DB Db2 SQL Replication deserialization in java Design Patterns designpatterns Downloads dtd Eclipse ejb example/sample code exception handling in core java file handling injava File I/O vs Memory-Mapped Filter first program in spring flex Garbage Collection Generics concept in java grails groovy and grails Guice Heap hibernate Hibernate Interview Questions how-to IBM DB2 IBM DB2 Tutorial ide immutable Interceptor Interface interview Interview Questions for Advanced JAVA investment bank j2ee java JAVA Code Examples Java 7 java changes java class loading JAVA Classes and Objects Java Classloader concept Java classloading concept java cloning concept java collection Java collection interview questions Java Collections java concurrency Java CountDownLatch java definiton Java design pattern Java EE 5 Java EE 6 Java Exceptions Java file Java Garbage Collection Java generics Java Glossary java hot concept java immutable concept Java Interface Java interview Question java interview question 2012 java interview question answer Java Interview Questions Java Interview Questions and Answers java interview topic java investment bank Java Job Questions java multithreading java multithreading concept java new features Java Packages java proxy object java questions Java Serialization Java serialization concept java serialization interview question java session concept java string Java Swings Questions java synchronization java threading Java Threads Questions java tutorial java util; java collections; java questions java volatile java volatile interview question Java Wrapper Classes java.java1.5 java.lang.ClassCastException JavaNotes javascript JAX-WS jdbc JDBC JDBC Database connection jdk 1.5 features JDK 1.5 new features Concurrent HashMap JMS interview question JMS tutorial job JSESSIONID concept JSESSIONID interview Question JSF jsp JSP Interview Question JSP taglib JSTL with JSP Junit Junit Concept Junit interview question.Best Practices to write JUnit test cases in Java JVM Linux - Unix tutorial Marker Interfaces MD5 encryption and decryption messaging MNC software java interview question musix NCR java interview question Networking Job Questions news Object Serialization Objects ojdbc14.jar OOP Oracle Oracle SQL Query for two timestamp difference orm own JavaScript function call in Apache ofbiz Packages Palm Apps patterns pdf persistence Portal Portlet Spring Integration Prime number test in java programs Rails Reboot remote computers REST Ruby Sample application schema SCJP security Senior java developer interviews servlet3 servlets session tracking singleton design pattern Spring Spring 2.5 Framework spring ebook Spring framework concept spring MVC spring pdf Spring Security Spring Security interview questions SQL SQL performance SQL Query to create xml file Sql Query tuning ssis and ssrs StAX and XML string concept string immutable string in java strings struts Struts2 Struts2 integration synchronization works in java Technical Interview testing tips Tomcat top Tutorial Volatile in deep Volatile working concept web Web Developer Job Questions web services weblogic Weblogic Application Server websphere what is JSESSIONID xml XML parsing in java XML with Java xslt


Monday, 29 July 2013

create dynamic HTML in JavaScript | Javascript code to add / remove rows dynamically in a table of HTML

This tutorial covers about how to add or  remove rows  in  a table of a HTML  dynamically  using javascript code .   HTML documets can be easily accessed and manipulated using HTML DOM , which represents an HTML document as a tree-structure.  When a  HTML document is  loaded in a browser window , it  becomes a Document object. Now we can use the Document object  to  access to all HTML elements  (as node objects) in a page, using  any script such as Javacript . Using  Document object ,  we can add or remove  element in the html as we do for  xml,  You can gothrough my earlier post to create xml using DOM .
              Let us see some of the following  HTML DOM properties and methods to access / modify the html documents , before writing the actual  program .

Some DOM properties:

nodeName - returns the name of an element
 nodeValue - returns the value of an element
 parentNode - returns the parent node of an element
 childNodes - returns the child nodes of element
 attributes - returns the attributes nodes of element

innerHTML -  to get or modify the content of  an element

   Suppose  x is a node object (HTML element) , the above properties can be accessed  as  x.innerHTML , x.nodeName, ....

Similarly some DOM methods:

getElementsByTagName(name) - get all elements with a specified tag name
 getElementById(id) - get the element with a specified id
 appendChild(node) - insert a child node to the element
 removeChild(node) - removes a child node from the element

eg. document.getElementById("tableId"), returns the table object.  you can insert , row & columns using the table object.
 to get the content (text)  of an element <p id="test">This is a test</p>  , you can use   innerHTML OR   childNodes and nodeValue properties with the method   getElementById

txt = document.getElementById("test").innerHTML;
 or
  txt=document.getElementById("test").childNodes[0].nodeValue;

Now let us design HTML table  and write javascript code to add or remove rows in a table .   Consider the web page to accept passenger details and child passenger details for booking ticket in a train or bus .

To accept  , passenger details , we need to  insert  rows and cloumns in a table ,  based on the first row  of the table.  The first row is mandatory to accept atleast one passenger details .



Table design with one row and heading



<H1>Passengers Details</H1>


    <TABLE id="PDetailsTable" width="350px" border="1">

     <tr>

       <td>SNO</td>

       <td>Name</td>

       <td>Age</td>

       <td>Gender</td>

       <td>Food Preference</td>

       <td>Berth Preference</td>

       <td>Senior Citizen</td>

       <td>Select to Delete</td>

   </tr>    



        <tr>



            <td> 1 </td>



            <td> <input type="text" name="name" /> </td>

            <td> <input type="text" name="age" /> </td>

            <td>  <select name="Gender">

                     <option value="M">Male</option>

                    <option value="F">Female</option>

                  </select>

           </td>

               

            <td> <select name="Food">

                    <option value="v">Veg</option>

                    <option value="nv">Non-Veg</option>

                </select>

            </td>

              

            <td> <select name="BerthPreference">

                    <option value="l">Lower</option>

                    <option value="m">Middle</option>

                    <option value="u">Upper</option>

                    <option value="sl">Side Lower</option>

                    <option value="su">Side Upper</option>

                </select> </td>

              

            <td><input type="checkbox" name="SCchk" /></td>

          

             <td><input type="checkbox" name="delchk" /></td>



        </tr>    </TABLE> 


Two input  buttons to call   addPassenger function  to insert dynamic row and to call deletePassengerRow  to remove row from the table dynamically.
  


   <input type="button" value="Add More Passengers" onclick="addPassenger('PDetailsTable')" />

    <input type="button" value="Delete Row" onclick="deletePassengerRow('PDetailsTable')" /> 

Two javascript functions  to add and remove dynamic rows and columns  and one more function ( arrangeSno)  to arrange serial numbers when the row is removed from the table are as follows




to arrange serial numbers



 function arrangeSno(tableId)

 {

             var tblObj = document.getElementById(tableId);

             var no_of_rows = tblObj.rows.length;

              for(var i=0; i<no_of_rows-1; i++)

           tblObj.rows[i+1].cells[0].innerHTML = i+1;

 }



To add rows dynamically based on the first row in a table



      function addPassenger(tableId) {


            var tblObj = document.getElementById(tableId);


            var no_of_rows = tblObj.rows.length;
    

// to insert single row

            var row_in_table = tblObj.insertRow(no_of_rows);


// to get the number of colums from the first row


             var colCount = tblObj.rows[0].cells.length;


// to increment sno from the previous row by one

           var rno=eval(tblObj.rows[no_of_rows-1].cells[0].innerHTML) +1;


            for(var i=0; i<colCount; i++) {


// to insert one column

               var column_in_row = row_in_table.insertCell(i);



                column_in_row.innerHTML = tblObj.rows[1].cells[i].innerHTML;

              

                if (i==0)  column_in_row.innerHTML = rno;



// to fill new row with  blank  text box, unchecked checkbox ,  combo selected with index 0 when the row is created , eventhough  the first row of the table having the textbox with filled values , etc...



                switch(column_in_row.childNodes[0].type) {

                    case "text":

                            column_in_row.childNodes[0].value = "";

                            break;

                    case "checkbox":

                            column_in_row.childNodes[0].checked = false;

                            break;

                    case "select-one":

                            column_in_row.childNodes[0].selectedIndex =0;

                            break;

                }

            }

        }





To remove rows dynamically  from the table .



        function deletePassengerRow(tableId) {

                    var tblObj = document.getElementById(tableId);

   
                 var delchkbox=document.bookingForm.delchk;    // where bookingForm is the form name


        var no_of_rows = delchkbox.length;

         for(var i=0; i<no_of_rows;i++)

         {

// heading and atleast one row should be in the table

         if (delchkbox[i].checked && tblObj.rows.length>=3)

         {

             tblObj.deleteRow(i+1);

                 no_of_rows--;

      i--;

          }

                }


          arrangeSno(tableId);        } 


To accept  ,child  passenger details ,  we are creating  elements like textbox , checkbox , dropdown list dynamically. These elements are inserted in the table's columns in a row  as a child element . Table rows and columns are also created dynamically . No row is mandatory . Table heading is displayed , if the table has atleast one row , otherwise , table heading is hidden.

Table design with heading without any initial rows



<H1>Child Passengers Details</H1>

  

    <TABLE id="childPassTable" width="350px" border="1" style="visibility:hidden" >

        <tr>

         <td>SNO</td>

         <td>Name</td>

         <td>Age</td>

         <td>Gender</td>

         <td>Select to delete</td>

    </tr>         </TABLE> 

Two buttons to call  addRowForChild &  deleteRowChild




 <P> <input type ="button" value="Add Child Passengers"  onclick="addRowForChild('childPassTable')">  <input type="button" value="Delete Row" onclick="deleteRowChild('childPassTable')"></P> 

Two javascript functions to add rows / remove rows in a table  and to create textbox , checkbox , combo box dynamically  for accepting child passenger details  .



    function addRowForChild(tableId) {



            var tblObj = document.getElementById(tableId);


            var no_of_rows = tblObj.rows.length;


// to make visible of the header row of the table , if the table has atleast one row
            if(no_of_rows==1)

             tblObj.style.visibility="visible";



// to insert one row of the table

            var row_in_table = tblObj.insertRow(no_of_rows);


//to insert the first column (for SNO)

            var column1 = row_in_table.insertCell(0);



      if (no_of_rows==1) 
         var rno=1;

     else
        var rno=eval(tblObj.rows[no_of_rows-1].cells[0].innerHTML) +1;


            column1.innerHTML = rno;


//to insert the second column (for textbox to accept name)

            var column2 = row_in_table.insertCell(1);

            var element2 = document.createElement("input");

            element2.setAttribute("name", "nameChild");  //to set name of the text box

            element2.type = "text";

            column2.appendChild(element2);


 //to insert the second column (for textbox to accept age)
            var column3 = row_in_table.insertCell(2);

            var element3 = document.createElement("input");

            element3.setAttribute("name", "ageChild");

            element3.type = "text";

            column3.appendChild(element3);


 //to insert the fourth column (for combo box to select gender)

            var column4 = row_in_table.insertCell(3);

            var combo = document.createElement("select");

            combo.setAttribute("name", "genderChild");

            var option = document.createElement("option");

            combo.options[0] = new Option("Male", 1);

             combo.options[1] = new Option("Female", 2);

            column4.appendChild(combo);

// to insert the fifth column (for check box )          

            var column5 = row_in_table.insertCell(4);

           var element5 = document.createElement("input");

            element5.type="checkbox";

            column5.appendChild(element5);

          

        }




       function deleteRowChild(tableId) {


            var tblObj = document.getElementById(tableId);

            var no_of_rows = tblObj.rows.length;


            var i=0;

            while (i<no_of_rows)

            {

                var row_in_table = tblObj.rows[i];

                var chkbox = row_in_table.cells[4].childNodes[0];

                if( chkbox !=null &&  chkbox.checked==true) {

                    tblObj.deleteRow(i);

                    no_of_rows--;

                    i--;

// to hide the table heading , if there is no row

            if(no_of_rows<=1) tblObj.style.visibility="hidden";

                }

                i++;

                }

              

             arrangeSno(tableId);

                   } 





Sample code to send / pass /  process the elements created  dynamically  in the page  to server side.            



  String[] names=request.getParameterValues("name");

  

  String[] birthPreference=request.getParameterValues("BerthPreference");



  String[] nameChild=request.getParameterValues("nameChild");

   .....

   .....

   .....

       for (int i = 0; i < names.length; i++)

    

          System.out.println("Name=" + names[i] + " Birth Preferance= " +  birthPreference[i] );

  

   .......   ........

No comments:

Post a Comment

LinkWithin

Related Posts Plugin for WordPress, Blogger...