Repeated Fields

If there is more than one field with the same name like in HTML input check boxes then the method to be used is getlist(). It will return a list containing as many items (the values) as checked boxes. If no check box was checked the list will be empty.

<html><body>
<%
import cgi

# Mentionining the form variable instantiates a FieldStorage object
# The getlist() method will return a list containing all the values
# of fields with a given name
colors = form.getlist('color')

if not colors:
   #
%>
<p>Check at least one color</p>
<%-- This form sets three fields with the name "color" --%>
<form method="post" action="">
Red<input type="checkbox" name="color" value="red">
Green<input type="checkbox" name="color" value="green">
Blue<input type="checkbox" name="color" value="blue">
<input type="submit" value="Submit">
</form>
<%
else:
   # Escape the user input to avoid script injection attacks
   colors = map(lambda color: cgi.escape(color), colors)
   #
%>
<p>The submitted colors were "<%= ', '.join(colors) %>"</p>
<p><a href="">Submit again!</a></p>
<%
#
%>
</body></html>