Friday, September 17, 2010

Multiple user selection using Checkbox

You need to allow user to select multiple values by using check boxes and storing them into an array. To do so, follow the steps given below :

//Enter the following code in the body tag of your HTML or JSP page.
<form action="servlet1">
   Your Hobbies : 
 //assign same value to the name property of the checkboxes.
   <input type="checkbox" name="hobby" value="Reading"/>Reading
   <input type="checkbox" name="hobby" value="Music"/>Music
   <input type="checkbox" name="hobby" value="Travelling"/>Travelling
   <input type="submit" value="OK"/>
</form>


//Enter the following code in the doGet() of the your servlet (in my case "servlet1").

 //assuming request as the object of the HttpServletRequest Class.
 //to retrive multiple value from the same named input control (in my case checkbox) use "getParameterValues()"
 //as multiple values are retrived, an array of String datatype can be used to store the values.

String[] myHobby = request.getParameterValues("hobby");

 //assuming response as the object of the HttpServletResponse Class.
 //to display values in the myHobby array, use for loop
for (int i = 0 ; i < myHobby.length ; i++) {
   response.getWriter().println(myHobby[i]);
   response.getWriter().println("     ");
}


Note : The same technique can be used to store values from multiple textboxes in to an array of String i.e. by assigning same name to the textboxes.

No comments:

Post a Comment