Open CheatSheet Back To List

Forms and Buttons (Video Tutorial)

Forms and Buttons

Intro to Forms and Buttons

Build a Blog Site: This is the tenth part of the Build a Blog Site tutorial series.
The focus of this tutorial is on Forms and Buttons.

Simulate Bootstrap: In this tutorial series we are mimicking Bootstrap classes, using the same Bootstrap class names, and applying the same or similar style but with less complex style rules.

Finished Code: The code is available on GitHub: github.com/LearnByCheating/learn-html-blog-site-example. There is a separate version with the finished code for each tutorial.

Live Server: If you are using VS Code as your text editor and have the Live Server extension installed, you can launch a local web server from the Editor.
  • Close any prior Live Server sessions by right-clicking in the editor, then select Stop Live Server.
  • If you are using the code from the GitHub link above, go to the .vscode/settings.json file and change the liveServer.settings.root value to the appropriate version: "liveServer.settings.root": "/v10-forms-buttons" 
  • Right click in the html page and select "Open with Live Server". 

Written and Video tutorial: There are both a video and written version of each tutorial. For the HTML-CSS tutorial series the video and written versions have a different focus. The video tutorials are focused on the blog site project. The written tutorial is focused on the all the subtopics within the CheatSheet major topic.

CheatSheet: Part of the objective of this tutorial series is to become familiar with the CheatSheet so you can use it for quick reference going forward. As such, it is recommended that you review the CheatSheet category that aligns with this tutorial.


Forms

You will generally have web forms when you are using a web framework like Express with Node.js. When the user submits the form, it is sent back to the web server and generally stored in, or checked against a database.

If our Blog Site example used a web framework and a database:
  • We would add a new article by filling out an article form. It would have fields for title, author, date, article content, whether it is published or a draft, and what category it is in. 
  • When the form is submitted, it would be sent back to the web server. Our web framework would save it to our database in an articles table. 
  • If a user of our Blog Site clicked the link to view an article, our web framework would pull the article data from the database. 
  • The article-template file would have placeholders for title, author, date, content, and category. 
  • The framework would insert the article data from the database into those placeholder locations of the HTML file. 
  • The framework would then send the article page back to the user's browser. 

Our site is not using a web framework or database, so we would have a separate file in the articles folder for each article. The file name would be a slug of the title. For example the file name for an article titled "Learn Web Development" would be articles/learn-web-development.html.
Replace spaces with dashes, remove special characters, and make it all lowercase.

Even though we are not using web forms in our Blog Site project, they are an important part of web development.
As such, we will create one for our sample-form.html page. 

We'll start with a simple HTML form with one field and no styling yet:
<form action="" method="POST">
  <div>
    <label for="title">Title</label>
    <input type="text" id="title" name="title">
  </div>
  <button type="submit">Save</button>
  <button type="reset">Reset</button> <a href="/">Cancel</a>
</form>

Let's go each of these tags and attributes.
  • form element: The form must be wrapped in form tags.
    • method attribute: The method attribute determines how the data is submitted back to the server. There are two options: GET and POST.
      • GET value: GET is the default value. GET puts the form data in the URL. GET requests are used by search engines, so you can see your search term at the end of the URL. You could even bookmark it with the search term.
      • POST value: For most forms, you don't want the data in the URL. To submit the form data without putting it in the URL, set method to "POST".
    • action attribute: Set the action attribute to the URL or path you are submitting the form data to. The web framework has code waiting at this URL to handle the form data. If you don't specify an action value, the data will be sent back to the same URL the form is on. 
  • Form fields: Each form field would generally be wrapped in a div element. This is not a requirement, but it makes it easier to segregate each field.
    • label tag: Use a label element to display the field name.
      • for attribute: The for attribute should be set to the id of the input element. Then if the user clicks the label it will put the cursor in the form field.
    • input tag: Form data is entered or selected in an input, textarea, or select element. 
      • id attribute: Include an id attribute to be used by the label. 
      • name attribute: This attribute is sent with the form data back to the web server. It will generally match the database field name if it is going to be stored in a database.
  • Button: At the bottom is a submit and optional reset button. They must be inside the form element. 
    • type="submit": The type attribute must be set to submit.
    • type="reset": You can optionally include a reset button. It will clear the form data when clicked.
  • Cancel Link: You may want to include a cancel link that goes back to some page on your site. You can style this to look like a button.

View the sample-form in the Blog Site project

To follow along and try out the examples below, you can open and launch the Blog Site v10 example project.

  • Open the Blog-Site-v10 project.
  • Launch Live Server: Before launching it, make sure you:
    • Shut down prior Live Server sessions 
    • and set .vscode/settings.json to /blog-site-v10.
  • View the form at http://localhost:5500/sample-form.html

Form Fields

There are several types of form fields. Our sample form will include the following:
  • <input type="text"...> Text input - for a single line of text.
  • <input type="date"...> Date input.
  • <textarea...>...</textarea> Textarea - for text that takes up more than one line.
  • <input type="checkbox"...> Checkboxes.
  • <input type="radio"...> Radio buttons.
  • <select type='select'...>...</select> Select Boxes.

Other common input types that we aren't putting in our example form include:
  • <input type="password"...> Password - For security, it doesn't display the characters the user types in.
  • <input type="email"...> Email - requires the value to be in email format.
  • <input type="number"...>  Number - only allows number values. 
  • <input type="tel" pattern="..."...> Tel - For entering phone numbers. Include a pattern attribute that lets you give a pattern that the number must match.
  • <input type="search"...> Search - Used in a search box for entering text.
  • <input type="hidden"...> Hidden - Not displayed to the user. You can use this for fields where there is only one option. That way it is submitted with the form, but the user doesn't see it.
  • <input type="time"...> Time
  • <input type="file"...> File - For file uploads, such as an image. Clicking it takes the user to their file system to find the file.

Other Input Element Attributes

We already discussed some of the input element attributes including id and name. 

Other useful attributes include:
  • size="100" Set the size of a text input element in number of characters. Default is 20.
  • autofocus automatically places the user's cursor in the form field. Applying this to the first form field with allow the user to just start typing without selecting the field first. 
  • placeholder="Some text" displays text in the field without setting the value. It disappears once the user enters a value.
  • value="Initial Value" sets the initial value of the field. Generally you would use value attributes in an edit form, populating each field with the existing values from the database. 
  • readonly user can read the value but not change it.
  • disabled disables the form field.

Validation Attributes:
Some attributes can be used for form validation.
  • required makes the field required. If the user tries to submit the form without filling out this field, the browser will display a message saying the field is required. 
  • minlength="2" maxlength="255" Sets the min/max length of characters in an input field. It won't let the user type more than the max, and won't allow the form to be submitted if less than the min.
  • min="1" max="100" step="10" For a number field, you can set the min/max/step increment number values.
  • min="2020-01-01" max="2050-12-31" step="600" For a date field, you can set the min/max date and step increments in seconds.
  • pattern="[A-Za-z]{10}" Input must match the regular expression pattern. This can ensure you get a consistent format for phone numbers, credit card numbers, etc.

Boolean attributes:
autofocus, readonly, disabled, and required are boolean attributes.
That means you don't assign values to them. The value is true if the attribute is present, and false if it is not. 


Bootstrap classes and our Stylesheet

Bootstrap classes
As usual we will be mimicking the Bootstrap classes.

Bootstrap documentation on Form styling is at: getbootstrap.com/docs > click Forms: Overview

Mimic-bootstrap stylesheet
Our form-related style rules in the mimic-bootstrap stylesheet are:

stylesheets/mimic-bootstrap.css
input, textarea, select { margin: 0; }
label { display: inline-block; }
.form-label { 
  margin-bottom: 0.5rem; 
}
.form-control { 
  display: block;
  width: 100%;
  padding: 0.375rem 0.75rem;
  border: 1px solid #ced4da;
  border-radius: 0.25rem;
  font-size: 1rem;
  line-height: 1.5;
  color: #212529;
}
.form-text {
  margin-top: 0.25rem;
  font-size: .875em;
  color: #6c757d;
}
.form-check-input {
  vertical-align: top;
  margin-top: 0.4em;
}
.form-check-label { margin-left: .25rem; }
.form-select {
  display: block;
  width: 100%;
  padding: 0.375rem 2.25rem 0.375rem 0.5rem;
  border: 1px solid #ced4da;
  border-radius: 0.25rem;
  font-size: 1rem;
}



Form Fields - tags and classes

Now we will go through the form fields used in our sample-form.html file and explain the tags and classes used.

Text Inputs
We have two short text input fields for title and author.
We already talked about the HTML tags for text input, so we'll mainly focus on the classes and style rules.


HTML:
<div class="mb-3">
  <label for="title" class="form-label">Title</label>
  <input type="text" class="form-control" id="title" name="title" placeholder="Enter full article title">
</div>
<div class="mb-3">
  <label for="author" class="form-label">Author</label>
  <input type="text" class="form-control" id="author" name="author" value="Joey R.">
</div>

CSS:
input, textarea, select { margin: 0; }
label { display: inline-block; }
.form-label { 
  margin-bottom: 0.5rem; 
}
.form-control { 
  display: block;
  width: 100%;
  padding: 0.375rem 0.75rem;
  border: 1px solid #ced4da;
  border-radius: 0.25rem;
  font-size: 1rem;
  line-height: 1.5;
  color: #212529;
} .form-text { margin-top: 0.25rem; font-size: .875em; color: #6c757d; }

Style Rules: In the stylesheet, we applied style rules to the below tags and classes:
  • input, textarea, select: We start by removing the the margin around the input, textarea, and select tags.
  • div.mb-3: For each form field div element, we add the mb-3 class to add 1rem (i.e., 16px) of margin at the bottom.
  • label: The default display property for label is inline-block, so the label doesn't take up the whole line. In our CSS we changed the display property to block for all label tags, so label now takes up the whole row.
  • .form-label: The .form-label class adds .5rem (i.e., 8px) of margin below the label.
  • .form-control: The form-control class is placed on the input elements. This makes the following changes:
    • Changes the display property from inline-block default to block so it takes up the whole row.
    • Sets width to 100% of the parent element's width.
    • Adds padding and a grey border with rounded corners.
    • Sets font-size to 1rem (i.e., 16px), line-height to 1.5, and color to charcoal.

We did use a couple HTML attributes in the inputs. 
  • Placeholder attribute: The title field has a placeholder attribute that gives some additional instructions. 
  • Value attribute: The author field has a value attribute. The value is populated in the form when it opens. 

Date Input
The date field uses an input element with type set to "date".
When the user clicks on the date field, the browser will display a date picker calendar that the user can use to select a date.

HTML:
<div class="mb-3">
  <label for="last-updated" class="form-label">Date</label>
  <input type="date" class="form-control" id="last-updated" name="last_updated">
  <div class="form-text">Enter last updated date.</div>
</div>
CSS:
.form-text {
  margin-top: 0.25rem;
  font-size: .875em;
  color: #6c757d;
}

  • Below the input element, we put a div with class form-text. This is an optional element to add more information or instructions for the field. It displays the text in smaller font that is grey colored.

Textarea
If a text field is going to be more than one line long, use the textarea element instead of input[type="text"].
<div class="mb-3">
  <label for="content" class="form-label">Content</label>
  <textarea class="form-control" id="content" name="content" rows="5"></textarea>
</div>

  • Opening and closing tags: Unlike the input element, textarea is not an empty element. It has an opening and closing tag.
  • rows attribute: By default it displays as two rows. You can add a rows attribute to display a specific number of rows.
  • Resizeable: The user can resize the textarea box by clicking and dragging the corner.
  • Display property: By default the display property is inline-block. The form-control class changed it to block.

Checkbox (select none, one, or more)
You can have one or more checkboxes for a field. 
<div class="form-check mb-3">
  <input class="form-check-input" type="checkbox" id="published" name="published" value="true" checked>
  <label class="form-check-label" for="published">
    Publish
  </label>
</div>

CSS:
.form-check-input {
  vertical-align: top;
  margin-top: 0.4em;
}
.form-check-label { margin-left: .25rem; }

  • Input[type="checkbox"]: An input tag with type set to checkbox will display as a checkbox. 
  • Value attribute: You must use the value attribute to assign a value.
  • Single checkbox: In the above example, we have a single checkbox for the published field. If checked,  the value "true" gets submitted.
  • Multiple checkboxes: You can have multiple checkboxes for the same field. For instance if we had a categories field, and an article could apply to multiple categories, then the user could check no boxes, one box, or multiple boxes.
  • Checked attribute: The optional checked attribute will check the box by default when the form opens.
  • We are not duplicating the Bootstrap styling for the form-check, form-check-input, and form-check-label. Bootstrap's style rules are quite complex. Ours use most of the defaults and still looks similar to Bootstrap.

Radio Buttons (select one)
To have the user select one of multiple predefined choices you can use radio buttons.
<div class="form-check">
  <input class="form-check-input" type="radio" id="draft" name="status" value="draft">
  <label class="form-check-label" for="draft">
    Draft
  </label>
</div>
<div class="form-check mb-3">
  <input class="form-check-input" type="radio" id="published" name="status" value="published" checked>
  <label class="form-check-label" for="published">
    Published
  </label>
</div>



  • Input[type="radio"]: An input tag with type set to radio will display as a radio button. 
  • Value attribute: You must use the value attribute to assign a value.
  • Name attribute: Only one radio button with the same name attribute can be selected. The browser will automatically unselect the previous value when a new one is checked.
  • In the above example, we have a field name status and two radio buttons with values draft and published.
  • Checked attribute: To preselect one of the radio buttons, add the checked attribute to it.
  • Radio buttons use the same classes as the checkboxes above.

Select Box (select one)
Instead of using radio buttons to select one option from a predefined list, you can use a select box, also called a drop-down box. 
We'll add a categories field with three category options: html, database, and javascript.

<div class="mb-3">
  <label for="category" class="form-label">Category</label>
  <select id="category" class="form-select" name="category">
    <option selected>Select category</option>
    <option value="html">HTML and CSS</option>
    <option value="database">Database</option>
    <option value="javascript">JavaScript</option>
  </select>
</div>

CSS:
.form-select {
  display: block;
  width: 100%;
  padding: 0.375rem 2.25rem 0.375rem 0.5rem;
  border: 1px solid #ced4da;
  border-radius: 0.25rem;
  font-size: 1rem;
}

  • select tag: Select boxes use the select element. Its default display property is inline-block.
  • .form-select: The form-select class changes the display property to block and sets width to 100% so it takes up the whole row. And we give it padding and a border with rounded corners.
  • option[value]: The select options go in option elements with the value in the value attribute.
    • Notice the first option does not have a value. It is displayed at the top and says "Select category", so it just serves as instructions. 
  • selected attribute: The selected attribute preselects the option.


Buttons

For the rest of this tutorial we will talk about button styling (see CheatSheet: Buttons category).

All forms have a submit button, and may have a reset button.
In addition, our sample-form has a Cancel link styled to look like a button. 

sample-form.html
<button type="submit" class="btn btn-primary">Submit</button>
<a href="/" class="btn btn-outline-secondary btn-sm ms-4">Cancel</a>


Bootstrap Button Classes

We are mimicking Bootstrap classes for our button styling.

Bootstrap documentation on Button styling is at: getbootstrap.com/docs > click Components: Button


Button Style rules

In our mimic-bootstrap stylesheet we are defining the style rules for the button tag and classes. Let's go through them one by one.

stylesheets/mimic-bootstrap.css
button {
  margin: 0;
  font-family: inherit;
  font-size: inherit;
  line-height: inherit;
}

For all button elements, we are:
  • Removing the margin.
  • Inheriting the font-family, font-size, and line-height from the parent element.

btn class: We applied the btn class to the submit button and the cancel link. It will not only customize the submit button, but will override the default anchor tag styling of the Cancel link, and make it look like a button.
.btn {
  display: inline-block;
  color: #212529;  
  text-decoration: none;
  padding: 0.375rem 0.75rem;
  cursor: pointer;  
  background-color: transparent;  
  border: 1px solid transparent; 
  border-radius: 0.25rem;
}

  • display: The button tag's default display property is inline-block, while the anchor tag's default display property is inline. This class sets display to inline-block so that it can have padding and margin on the top and bottom.
  • text-decoration: Setting this to none removes the underline from links.
  • cursor: Change the cursor from the default cursor to the pointer.
  • Set the text color to charcoal, add padding, and make the background color transparent.
  • Make a rounded transparent border.

Add color to the button:
In addition to the btn class, the submit button has a class named btn-primary that will add a blue color to it.
<button type="submit" class="btn btn-primary">Submit</button>

.btn-primary {
  color: #fff;
  background-color: #0d6efd;
  border-color: #0d6efd;
}
.btn-primary:hover {
  background-color: #0a58ca;
  border-color: #0a58ca;
}

  • The text color #fff is white.
  • The background and border colors are set to a shade of blue.
  • When the user hover's the mouse over the button, the background and border color changes to a darker shade of blue.

The cancel button is similar but uses an outline style and a different color, gray.
< a href="/" class="btn btn-outline-secondary btn-sm ms-4">Cancel< /a>

.btn-outline-secondary {
  color: #6c757d;
  border-color: #6c757d;
}
.btn-outline-secondary:hover {
  color: #fff;
  background-color: #6c757d;
  border-color: #6c757d;
}

  • The text and border are colored gray, but the background remains transparent.
  • On hover the text color changes to white, and the background and border colors are set to gray.

Change button size
Also notice the cancel link has a class of btn-sm.

.btn-sm {
  padding: 0.25rem 0.5rem;
  font-size: .875rem;
  border-radius: 0.2rem;
}

That reduces the size of the padding, font, and border radius.

View the changes
Save the changes to the stylesheet and the sample-form.html file, then view the result in the browser:
http://localhost:5500

To see if the display looks the same when using the Bootstrap CDN:
  • Comment out the local stylesheets/styles.css.
  • Uncomment the Bootstrap CDN link.
  • Refresh the page. It should look nearly identical. 
  • Now switch it back. Comment out the Bootstrap CDN and uncomment the local stylesheet.



Use the Blog Site project for an actual blog site


To use this project for an actual blog site you need to do the following:
  • Purchase a domain name from a domain name Registrar and point it to your web host. For a domain name that is not in demand, something specific to you like your name, it costs around $20 per year. 
  • Choose a web host. You can actually host websites that only contain HTML, CSS, and images (no JavaScript or Database) on GitHub for free using GitHub Pages. 
  • Customize the content, like Site name, About section, etc.
  • For actual articles, copy the article-template page and change the file name to the title of your article, followed by the .html extension. Then change the content, including the Table of Contents (or remove the table of contents). Add images if desired. Then change the article summary in the index.html page. 
Open CheatSheet Back To List