Overview

When you want to get information from users who visit your website, you can use HTML forms. An HTML form is made of form controls (as known as widgets). These form controls can be text fields, select boxes, buttons, checkboxes, radio buttons, etc. Most of the time these form controls are paired with a label that describes their purpose. Through an HTML form, a web page asks the user to enter data and then that data collected by the form can be sent to a web server.

You will: (1) create an HTML form that allows users to enter a wildlife road collision incident, (2) apply CSS styles to the collision report form, (3) implement JavaScript event handler functions to handle user and browser actions, and (4) validate the data collected by the form.

1. Creating a Form in a Collision Report Page

  • report_collision.html

2. Applying Styles to Collision Report Form

  • report.css

3. Event Handling with JavaScript

  • report.js

4. Form Validation with HTML attributes and JavaScript

  • report_collision.html
  • report.js

Part 1 - Creating a Form in a Collision Report Page

Create a collision report page composed of form controls. The page allows a user to enter a wildlife road collision data onto the page. This page includes a heading and a form element. Part 1-1 - Setup the Form Element

Figure: see image.

As you see in the layout above, you will divide the form into several rows consisting of two columns: a label and a form control. You can display the labels on the left, and the input fields on the right. A submit and a cancel button will be placed on the last row and floating to the right.

1. Create a working folder for the Lab 9 assignment (e.g. c:\geog646\lab9\). Launch Visual Studio Code and click File -> Open Folder. Navigate to the folder you created and open it.

2. Right click on the folder (lab9) on Explorer in Visual Studio Code, click "New File", and create a new HTML file. The file name is up to you. (e.g. reportCollision.html)

3. Include < !DOCTYPE >, < html >, < head >, < body > elements in reportCollision.html

4. To specify character encoding, add tag to the head section as follows: < meta charset="utf-8" / >

5. Insert your title (e.g. Report a Collision) between < title > and < /title > in the head section.

Add a content < div > element to the body of the page and set its id to "content", which will be used to style the content div.

7. Add a heading to the content div, e.g. "Report a Wildlife Collision".

8. In the content div, add a < form > element and set its id to "report".

9. Next, set the form's method attribute to "post" and its action attribute to https://geogws003.umd.edu/collision_record.php so form data will be sent to the specified server-side script, "collision_record.php" as a post request. In this lab, you will use the PHP script implemented by the instructor.

Note: For now, don't worry about the PHP. You will learn PHP in GEOG657!

< body >
< div id="content" >
< h2 >Report a Wildelife Collision< /h2 >
< form method="post" id="report" name="report" action="https://geogws003.umd.edu/collision_record.php" >
< /form >
< /div >
< /body >

10. This page allows a user to enter information about a wildlife road collision case containing 'Species', 'Gender', and 'Age' of a victim, and 'Report Date' and 'Location' description and 'Longitude', and 'Latitude' of a collision and defined by the following variables:

Variable Description Input Type Name
Species A select menu for species name select species
A text field if user selects "Others" text txtSpecies
Report Date A text field for date date rpDate
Location A text field for string text location
Latitude A text field for numeric number lat
Longitude A text field for numeric number lng
Gender Grouped radio buttons radio rbGender
Age Class Grouped radio buttons radio rbAge

Important Notes About Form Input Elements:

  • For each of the variables above, we will add a form control to the page.
  • A label will be specified and associated with each form control as needed.
  • The "name" attribute of each form element must match the names listed above exactly.

11. Between < form > and < /form > tags, add a < div > element to group a < select > element and associated < label > element. This will be done for each variable above. Start with "Species".

Note: Each form element and its label are grouped together in a < div > element. Form controls are in-line elements so they will display in a line without grouping them in a div (block) element.

12. For the "Species" variable, we need to provide a list of species to select. Populate a set of < option > elements in the < select > element to make a drop-down select menu as follows:

< div >
< label for="species" >Species: < /label >
< select id="species" name="species" >
< option value="" >Select a species< /option >
< option value="Bear" >Bear< /option >
< !-- ADD EIGHT (8) Other options
(e.g. Deer, Skunk, etc...)
for the Dropdown Menu -- >
< /select >
< /div >

13. The option for "Bear" is above. On your own, add eight (8) other options for "species".

14. Set id and name attribute of the select menu. For simplicity, make id and name the same.

15. Above the < select > element, add a < label > element and set the for attribute to the same value as the id of the < select >, so they can be linked together.

16. After < select > element, add a text field to allow users to enter a new species if the dropdown list does not include a matched species (i.e. if they select "Others"). Add a < div > to group a < input type="text" > element and an empty label element associated with the text field.

17. Set its id and name attribute of the text input. Specify a short hint that describes the expected value of the text input using the placeholder attribute.

< div >
< label for="txtSpecies" > < /label >
< input type="text" id="txtSpecies" name="txtSpecies" placeholder="Type in a new species" / >
< /div >

Figure: see image.

Part 1-2 - Add Additional Input Elements

19. Add a < div > with an < input type="date" > and a < label > element for the "Report Date". This will allow users to enter the date of the collision. Set the id and name properties.

20. To allow a user to enter a text description of the "Location", add an input text element and an associated label element wrapped in a div. Set the id, name, and placeholder attributes of the input text field. The placeholder can be whatever you feel is appropriate.

21. Add a text field and a label for the "Latitude" of the collision. Use < input type="number" >. Set the id and name properties. Set the initial value to whatever you feel is appropriate.

22. Add a text field and a label for the "Longitude" of the collision. Use < input type="number" >. Set the id and name properties. Set the initial value to whatever you feel is appropriate.

23. Next, group radio buttons for the "Gender" selection, which allows users to select one option from grouped radio buttons.

24. Add three radio buttons associated with labels: "Male", "Female" and "Unknown".

25. You need to add a label (e.g. Gender) for the grouped radio buttons. The label and the three radio buttons are wrapped in a div.

< div >
< label >Gender:< /label >
< label >< input type="radio" name="rbGender" value="male" >Male< /label >
< label >< input type="radio" name="rbGender" value="female" >Female< /label >
< label >< input type="radio" name="rbGender" value="unknown" >Unknown< /label >
< /div >

26. In a similar way, create a form control for the "Age" variable. Make grouped radio buttons for three age classes ("Juvenile", "Adult", "Unknown") of wildlife.

27. Next, add a < div > element containing "Cancel" and "Submit" buttons.

28. Save and view the page in a web browser. Your page should look like the figure below.

Figure: see image.

On your own, make the text field named "txtSpecies" not editable. Review and compare the disabled and readonly properties. Which HTML attribute could you use to prevent a user from typing in a text field but still send data to the server on submit? Add the appropriate attribute to make the text field not editable in reportCollision.html.

Part 2 - Applying Styles to Collision Report Form

Part 2-1 - Dividing the Layout into Rows and Columns

The current layout of the form doesn't look very good. Change the layout and styles of the form using CSS like the following figure. This form is divided into 9 rows consisting of 2 columns: a label and a form control. You will display the first column on the left, and the second column on the right. A submit and a cancel button will be placed on the last row and floating to the right.

Figure: see image.

1. First, set the class property of all the wrapper elements (i.e. div element) for each row (which contains a label and a form control) to "row".

< div class="row" >
< label for="species" >Species:< /label >
< select id="species" >...
< /select >
< /div >

< div class="row" >
< label for="txtSpecies" >< /label >
< input type="text" id="txtSpecies" name="txtSpecies" placeholder="Type in a new species"/ >
< /div >
.....

2. Add a wrapper element (i.e. div element) for the first column in each row and set the class property to "col-25". For example:

< div class="row" >
< div class="col-25" >
< label for="species" >Species:< /label >
< /div >
< div class="col-75" >
< select id="species" name="species" >
< option value="" >Select a species< /option >
< option value="Bear" >Bear< /option >
< !-- ADD EIGHT (8) Other Options
(e.g. Deer, Skunk, etc...)
For the Dropdown Menu -- >
< /select >
< /div >
< /div >

3. Add a wrapper element (i.e. div element) for the second column in each row and set the class property to "col-75".

4. Next, you will apply CSS styles to the elements in the report page. Click New File and create a CSS file. Type a filename of your choice (e.g. report.css)

5. Make a link to the external stylesheet (report.css) in the head section of the HTML page using < link > tag.

6. To display the first column (e.g. a label element) to the left and the second column next to the first column, apply the float property to the through col-25 and col-75 class selectors. Note that you must set the width property to the columns to make them float. Set the width of the first column to 25% and the second column to 75%.

7. To display a next row, clear the float after each row. Hint: Use CSS pseudo-elements to select "after" each row. https://www.w3schools.com/css/css_pseudo_elements.asp

8. Save reportCollision.html and report.css files and preview the page.

Figure: see image.

Part 2-2 - Adding Additional Styles to Form Elements

9. Apply the following to the text fields, number fields, date fields, and select menu. Hint: Use CSS attribute value selectors. https://www.w3schools.com/cssref/sel_attribute_value.asp

  • Set the width to 100% to make the form controls span the entire container's width
  • Set the background-color and color of the content text
  • Set the border and border-radius properties

10. Save the CSS file and preview the page.

Figure: see image.

Although you applied the same width (i.e. 100%) to the form controls, they don't have the same width as you see the following figure. Each form control has its own rules for border, padding and margin and its border and padding are added to the element's width/height.

11. To get around this problem, set the box-sizing property to border-box. It will make element padding and border included in the width and height.

12. Save the CSS file and view and check the page in a browser.

Figure: see image.

13. Change the font-family, font-size, font-style, padding, and color of the headings and labels.

14. Set the id of the < form > element and apply the following styles using an ID selector:

  • Set the background-color
  • Set the border-radius
  • Set the padding

15. Save the files and view the page in a browser.

Figure: see image.

16. Apply the following styles to the "Submit" and "Cancel" buttons.

  • Set the background-color
  • Set the color of the content text
  • Set the border-radius
  • Set the padding and margin
  • Set the cursor property to specify the mouse cursor when pointing over an element
  • Make it float to the right of its container

17. Set a different background-color when users move a mouse over the Submit or Cancel buttons with a pseudo selector. https://www.w3schools.com/css/css_pseudo_classes.asp

18. Save the files and view the page in a browser. What happened? You may see the form control elements overflow the border of its container (i.e. form) as the following figure.

Figure: see image.

Why did this problem happen? How could you solve this problem? Review and compare the float, clear, and clearfix properties. Think about two different ways to fix the floating element overflowing its container. On your own, update your CSS file to fix this issue.

Your page should look like the following figure after you finish your CSS code.

Figure: see image.

Part 3 - Event Handling with JavaScript

In this part, you will implement JavaScript event handler functions to handle user and browser actions. When users select an option of the dropdown menu, you will enable and disable user's input to the text field named "txtSpecies" using JavaScript.

1. Create a folder for JavaScript files (e.g. js) and create a JavaScript file (e.g. report.js).

2. Open reportCollison.html and add a < script > tag in the head section to reference the custom JavaScript file from HTML page.

3. Define and set an event handler function (e.g. initForm()) for the "page load" event so that this function will be called when a page is loaded.

4. In this function, you set another event handler (e.g. toggleToEnterNewSpecies()) function for the change event of the drop-down menu control so that you enable the "txtSpecies" input text field only if "Others" option is selected from the drop-down list. Note: The function names are up to you.

window.onload = /*complete code here*/

function initForm() {
document.getElementById("species").onchange = /*complete code here*/
}

function toggleToEnterNewSpecies() {
}

5. In toggleToEnterNewSpecies() function:

  • Get the drop-down menu control element using document.getElementById().
  • Get the value of the selected option using the options and selectedIndex attributes of the < select > element.
  • If the value of the selected option is equal to "Others", make the text field named "txtSpecies" editable using removeAttribute(). Otherwise, set an empty string ("") to the text field and make the text field not editable by using setAttribute(). https://www.w3schools.com/jsref/met_element_setattribute.asp

Note that setAttribute() requires two input parameters. It won't work with only one!

Figure: see image.

Part 4 - Form Validation with HTML Attributes and JavaScript

Part 4-1 - Form Validation with HTML Attributes

1. You can make an input element mandatory using the required attribute. When users don't enter data to the required input field, they will get the message like "This field is required".

2. Open report_collision.html. Add the required attribute to the following form control elements so you can ensure users won't leave them blank when they click the submit button.

  • Species, Gender, Report Date, Location

3. The min and max attributes also provide a validation constraint. If the field's value is lower than the min attribute or higher than the max attribute, the field will be invalid. Specify the min, max, and step attributes of the following input elements using appropriate values.

  • Latitude, Longitude

Part 4-2 - Form Validation with JavaScript

4. Open report.js. Define an event handler function named validateForm(), which will be called when the "submit" button of the "#report" form is clicked.

window.onload = /*complete the code here*/

function initForm() {
document.getElementById("species").onchange = /*complete the code here*/
document.getElementById("report").onchange = /*complete the code here*/
}

function toggleToEnterNewSpecies(){
/*complete the code here*/
}

function validateForm(){
/*complete the code here*/
}

5. In initForm() function, assign an event handler function, validateForm() to the onsubmit event property of the form. When the submit button is clicked, it will call and execute validateForm().

6. In validateForm () function, you will get the data entered by users, display the data in a dialog window, make users check and confirm the data before it is sent to the server.

  • Access each form control using document.getElementById(), get its value, and store it in a variable.
  • Declare a flag variable (e.g. allGood) that stores whether data is valid or not (true or false). Assign true initially.
  • The Latitude and Longitude input fields are not required so it could have an empty string.
    • If the input field has "" (empty string), display a confirm dialog to ask users to confirm that the empty string to be sent to the server.
    • The confirm() method returns true if the user clicked "OK". Otherwise false. Assign the returned value from confirm() to the variable allGood.
    • If allGood is false, give a focus to the input field and return false.

Figure: see image.

  • Display a confirm dialog with the all the input values collected by the form and ask the user to confirm the info. Assign the returned value from confirm() to allGood.

Figure: see image.

  • Most of the form inputs are straightforward, but the radio buttons (Gender and Age) are a bit tricky. It's easiest with Query Selector. Think of it as selecting an element based on a CSS selector. https://www.w3schools.com/jsref/met_document_queryselector.asp
    • In this case we want to select an input element based on the name attribute. Remember we could do something like this: input[name="rbGender"]
    • But we only want to select the checked one. We can use a pseudoclass selector (https://www.w3schools.com/css/css_pseudo_classes.asp) like this: :checked
    • Put them together to build the query selector!
  • Return the value of the flag variable, allGood at the end of the function
    • If you return false, the PHP script is not called and the user must fix the field.
    • If you return true, the valid data is sent to the PHP script. In this lab, you will send the data to the PHP script implemented by the instructor available at: https://geogws003.ad.umd.edu:8443/resop/geog646/lab9/collision_record.php
    • This PHP script will generate a dynamic HTML page containing the collision record entered by the user.

7. Modify the toggleToEnterNewSpecies() function. When the user selects the option "Others", make the text field named "txtSpecies" required using setAttribute() method. Otherwise, remove the required attribute using removeAttribute() method.

8. Save reportCollision.html and report.js and view the page. Enter test data and click "Submit". Click "OK" of the confirm dialog. You may see an error page like below.

Figure: see image.

To get around this problem, connect to the UMD network systems using VPN. Install GlobalProtect to connect using VPN. You can download it here: https://maestro.listserv.umd.edu/trk/click?ref=zvb24p867_2-17bwv7k-7-36c5x3366fx03557&

9. After you connected to the UMD network using VPN, view the page in a browser and enter test data and click "Submit". Click "OK". You may see the HTML page generated by the server-side PHP file, collison_record.php like the following figure.

Figure: see image.

On your own, modify your web form so it also includes validation for the Date value. Specifically, force the Date to only be valid for the current calendar year (e.g. January 1st 2022 to December 31st, 2022). We discussed both HTML validation and JS validation. Choose the method you feel is most appropriate for this problem.

Academic Honesty!
It is not our intention to break the school's academic policy. Posted solutions are meant to be used as a reference and should not be submitted as is. We are not held liable for any misuse of the solutions. Please see the frequently asked questions page for further questions and inquiries.
Kindly complete the form. Please provide a valid email address and we will get back to you within 24 hours. Payment is through PayPal, Buy me a Coffee or Cryptocurrency. We are a nonprofit organization however we need funds to keep this organization operating and to be able to complete our research and development projects.