Blog Archive

Dynamically add form elements using jQuery such as Input Textbox, Radio Buttons, Checkboxes, Dropdown and Submit Button

In this example we add various form elements on the page programmatically using jQuery and then process them using Java Servlet. It's a very common requirement to add an extra input field on the web page after an user selects a Checkbox or clicks a Button. You can either choose to have all those elements hidden (sometimes cumbersome to do depending on the program logistics) in the form and then display them based on user action or create them on the fly as you need them. In this tutorial we are going to learn how to do the later.


Dynamic form processing using jQuery and Java Servlet
Dynamically add form elements using jQuery

HTML Source Code

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<meta name="robots" content="noindex,nofollow" />
<title>Dynamic form processing using jQuery and Java Servlets</title>
<link rel="stylesheet" href="/resources/themes/master.css" type="text/css" />
<link
 href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css"
 rel="stylesheet" type="text/css" />
<script
 src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"
 type="text/javascript"></script>
<script
 src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"
 type="text/javascript"></script>
<script src="/resources/scripts/mysamplecode.js" type="text/javascript"></script>

<script type="text/javascript">
$(document).ready(function() {

 var counter = 0;
 
 $("#addElement").click(function(event){
  
  counter++;
  var $selection = $("input[name='selection']:radio:checked").val();
  
  switch ($selection) { 
         
   //add Input Text Box
   case 'A': 
    var $newDiv = $("<div>Input Box: </div>");
    var $newInput = $("<input type='text'>");
    $newInput
      .attr("name", "fieldName" + counter)
      .addClass("text");
    $newInput.appendTo($newDiv);
    $newDiv.appendTo($("#generatedForm"));
          break;
        
         //add Radio Buttons 
         case 'B': 
          var numberOfButtons = Math.floor((Math.random()*10)+1);
          var $newDiv = $("<div>Radio Buttons: </div>");
          for(var i=0;i<numberOfButtons;i++){
           var $newInput = $("<input type='radio'>");
     $newInput
      .attr("name", "fieldName" + counter)
      .attr("value", "RadioButton" + i)
      .addClass("text");
     if(i==0){
      $newInput.attr('checked',true);
     }
     $newInput.appendTo($newDiv);
     $newDiv.appendTo($("#generatedForm"));
     $newInput.after("RadioButton" + i);
          }
          break;
          
         //add Checkboxes 
         case 'C': 
          var numberOfButtons = Math.floor((Math.random()*10)+1);
          var $newDiv = $("<div>Checkboxes: </div>");
          for(var i=0;i<numberOfButtons;i++){
           var $newInput = $("<input type='checkbox'>");
     $newInput
      .attr("name", "fieldName" + counter)
      .attr("value", "Checkbox" + i)
      .addClass("text");
     if(i==0){
      $newInput.attr('checked',true);
     }
     $newInput.appendTo($newDiv);
     $newDiv.appendTo($("#generatedForm"));
     $newInput.after("Checkbox" + i);
          }
          break;
          
         //add Dropdown
         case 'D': 
          var numberOfButtons = Math.floor((Math.random()*10)+1);
          var $newDiv = $("<div>Dropdown: </div>");
          var $dropDown = $("<select></select>");
          $dropDown.attr("name", "fieldName" + counter);
          
          for(var i=0;i<numberOfButtons;i++){
           var $newInput = $("<option></option>");
     $newInput
      .attr("value", "Option" + i)
      .addClass("text")
      .html("Option" + i);
     $newInput.appendTo($dropDown);
     $dropDown.appendTo($newDiv);
     $newDiv.appendTo($("#generatedForm"));
    }
          break;
          
         //add Button
         case 'E': 
          var $newDiv = $("<div>Just a button: </div>");
    var $newInput = $("<input type='button'>");
    $newInput
      .attr("name", "fieldName" + counter)
      .attr("value", "Button" + counter)
      .addClass("text");
    $newInput.appendTo($newDiv);
    $newDiv.appendTo($("#generatedForm"));
          break;
  } 
 });
 
});
</script>
</head>
<body>
 <div id="allContent">
 <%@include file="/header.jsp"%>
  <div id="myContent">
   <div>
    <table>
     <tr>
      <td>
       <input type="radio" name="selection" value="A" checked/> Input Text
       <input type="radio" name="selection" value="B" /> Radio Buttons
       <input type="radio" name="selection" value="C" /> Checkboxes
       <input type="radio" name="selection" value="D" /> Dropdown
       <input type="radio" name="selection" value="E" /> Button
      </td>
     </tr>
     <tr>
      <td>
       <input id="addElement" type="button" value="Add to Form" />
      </td>
     </tr>
    </table>
   </div> 
   <form id="samplecode" name="samplecode" method="POST" action="<%= request.getContextPath() %>/DynamicForm">
     <fieldset>
      <legend><b>&nbsp;&nbsp;&nbsp;Dynamically added form elements&nbsp;&nbsp;&nbsp;</b></legend>
      <div id="generatedForm">
       <div>
        <input id="processForm" type="submit" value="Submit to Process" />
       </div>  
      </div>
     </fieldset>
   </form>
  </div>
 </div>

 <%@include file="/footer.jsp"%>
 <div></div>
</body>
</html>

Java Servlet Source Code

package com.as400samplecode;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DynamicForm extends HttpServlet {
 private static final long serialVersionUID = 1L;

 public DynamicForm() {
  super();
 }

 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  doPost(request,response);
 }

 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


  StringBuilder sb = new StringBuilder();
  sb.append("<html>");
  sb.append("<head><title>Dynamic form processing</title></head>");
  sb.append("<body>");
  sb.append("<h1>Reading All Parameters</h1>");

  sb.append(startDiv() + "<table width=\"100%\">");
  @SuppressWarnings("unchecked")
  Enumeration<String> paramNames = request.getParameterNames();
  while(paramNames.hasMoreElements()) {
   String paramName = paramNames.nextElement();
   String[] paramValues = request.getParameterValues(paramName);
   sb.append(addContent(paramName,printValues(paramValues)));
  }
  sb.append("</table>" + endDiv());

  sb.append("</body>");
  sb.append("</html>");

  response.setContentType("text/html");
  PrintWriter out = response.getWriter();
  out.println(sb.toString());

 }

 private String startDiv(){
  return "<div style=\"background:#eeeeee\">";
 }

 private String endDiv(){
  return "</div><br/>";
 }

 private String addContent(String text, String value){
  return  "<tr>" +
  "<td width=\"10%\" valign=\"top\">" +
  text.trim() + 
  (value.trim().equalsIgnoreCase("") ? "" : ": ") +
  "</td><td valign=\"top\">" + 
  value.trim() +
  "</td>" +
  "</tr>";
 }

 private String printValues(String[] paramValues){

  StringBuilder sb = new StringBuilder();
  if (paramValues.length == 1) {
   sb.append(paramValues[0]);
  } else {
   sb.append("<ul>");
   for(int i=0; i<paramValues.length; i++) {
    sb.append("<li>" + paramValues[i]);
   }
   sb.append("</ul>");
  }
  return sb.toString();
 }

}