HTML Forms

HTML Language

Forms

With HTML Forms, you can record information from the user. In this lesson, we will discuss the HTML portion of the form, and the basics of capturing the user's input to the form with Python CGI programming.


Format

Here is an example:

<!DOCTYPE html>
<html>
 <body>
  <!--The <form> tag defines a form element-->
  <form>
   <!--Directly add text in a form element-->
   Are you a returning or new user?<br />
   <!--input type="radio" creates single selection radio buttons-->
   <input type="radio" name="new_or_returning" value="Returning" />Returning<br />
   <input type="radio" name="new_or_returning" value="New" />New<br />
    Returning users:<br />
     Username: <input type="text" name="Username" /><br />
     Password: <input type="password" name="Password" /><br />
     <input type="submit" value="Sign In" /><br /><br />
    Create an account:<br />
     Username: <input type="text" name="Create_Username" /><br />
     Password: <input type="password" name="Create_Password" /><br />
     E-mail: <input type="text" name="E-mail" /><br />
     <input type="submit" value="Create Account" />
  </form>
 </body>
</html>

A form element is defined in the <form> tag, in which you can include text and other elements such as <input>s. You can create a small input text area with the <input type="text"> tag. You can create a single selection from <input type="radio">. Use <input type="checkbox"> to create checkboxes. Create submit buttons with type="submit". To create a larger, resizable textarea, use the <textarea> tags. You can define its width and height with attributes, and what you put between the starting and ending tags will appear as initial value in the text area. The name area is used to differientiate different input elements and use in CGI.


Recording Input

To record and store the user's input, CGI (Common Gateway Interface) can be used. (You may need to configure Apache to enable CGI scripts to be ran) Here, we will demonstrate basic CGI with Python:

<!DOCTYPE html>
<html>
 <body>
  <form action="add.cgi" method="POST">
   Enter two numbers to add:<br />
   First Number: <input type="text" name="num1" /><br />
   Second Number: <input type="text" name="num2" /><br />
   <input type="submit" value="Add" />
  </form>
 </body>
</html>

#!/usr/bin/python

import cgi
import cgitb
cgitb.enable()

input_data=cgi.FieldStorage()

print 'Content-Type:text/html' #HTML is following
print                          #Leave a blank line
print '<h1>Addition Results</h1>'
try:
  num1=int(input_data["num1"].value)
  num2=int(input_data["num2"].value)
except:
  print '<p>Sorry, we cannot turn your inputs into numbers (integers).</p>'
  return 1
sum=num1+num2
print '<p>{0} + {1} = {2}</p>'.format(num1,num2,sum)'



Practice

Create a simple form and try to add some formatting.


Tags

Tag Meaning
<form> Defines a form element
<input> Defines an input element
<textarea> Defines a textarea



<< Previous TOC Next >>