In this module, you will use structured semantic data to control how web sites appear to the user. You will create semantic HTML to structure webpages to look good and work well.
Learning Objectives
- Create a video and audio player that can rate the media played.
- Post form data to a server
- Recognize server-side connections and the languages used to carry out requests and responses.
- Create and test a form with client-side validation.
- Create commonly-used web page layouts and components.
- Use common semantic and meta tags to improve the accessibility, readability and SEO of a web page.
Course Introduction
Video: Introduction to the Program
Become a Front-End Developer in One Year: No Experience Needed!
This Meta Professional Certificate program equips you with the skills to become a job-ready front-end developer in just one year, even if you have no prior tech experience.
Here’s what you’ll gain:
- Learn from Meta developers: Gain insights into their collaborative process and how they build high-performing websites and applications.
- Master the fundamentals: Build interactive web pages using HTML, CSS, and JavaScript.
- Leverage powerful tools: Utilize Bootstrap and React, a popular Meta-created JavaScript library, to create fast, scalable, and user-friendly websites.
- Build your portfolio: Showcase your skills by creating a professional website with interactivity.
- Prepare for the job hunt: Learn how to collaborate with other developers using Git and GitHub, practice interview skills, and refine your resume.
- Gain career support: Get access to the Meta Career Programs Job Board, connecting you with potential employers.
This self-paced program offers:
- Flexibility: Learn at your own pace and manage your time effectively.
- Community: Connect with other aspiring developers and share your journey.
- Industry-recognized credential: Earn a certificate from Meta upon completion.
Ready to shape the future of connection? Enroll in the program today!
The digital space is a world
of connection and opportunity. Take this moment for example, the web has
made it possible for you to enroll in this program where you will learn from the
personal stories of developers at meta. Isn’t that exciting? By the time you have completed
this professional certificate, you can become a creator
of digital experiences. Connection is evolving and so are you. You might not have a background
in tech at all and that’s okay. Even if you have no experience, this program can get your job
ready within a single year. So, how can this professional
certificate prepare you for a job at an organization like meta? The front end developer professional
certificate will help you build job ready skills for a front end development role
while earning a credential from meta. From meta developers you will learn
about how they collaborated, create and test responsive, high performance
websites and applications. You’ll also discuss interesting
topics with other aspiring front end developers and complete a range of
coding exercises to improve your skills. It’s important to complete
all the courses in the certificate in order as each
course will build on your skills. Although we have a recommended
schedule for each course, the program is entirely self paced, which
means your time is your own to manage. As you make your way through the first
four courses in the certificate, you’ll learn how to code interactive web
pages using HTML, CSS and JavaScript. You’ll also learn how to use the bootstrap
framework before diving into the world of React, a widely used JavaScript
library that was created here at meta. Websites built using React are fast,
scalable, secure and allow for rich user experience. It’s no wonder it’s the choice
of leading companies. For your final project you will complete
a beautiful professional website for your portfolio, complete with interactivity
to showcase during your job search. You’ll also be ready to collaborate
with other developers as you will have learned to use GIT and
GIT hub for version control. If you’re hoping to operate independently
or in a smaller team, not to worry. We’ve also got you covered when it
comes to the basics of user experience. You’ll learn how to research
a user’s needs, create wire frames using popular industry tools like
Figma and design interactivity. In the final course, you will prepare for
the coding interview. You’ll practice your interview skills,
refine your resume and tackle some common coding challenges that typically
form part of technical job interviews. Once you complete the program, you’ll get access to
the meta career programs job board. A job search platform that connects you
with over 200 employers who have committed to sourcing talent through
meta certificate programs. Who knows where you’ll end up? Whatever the future of connection looks
like, you’ll be part of its creation. Let’s get started.
Video: Introduction to HTML and CSS in depth
Dive into Web Development: Learn HTML, CSS, and More!
This course offers a comprehensive introduction to building websites using HTML and CSS.
What you’ll learn:
- HTML Fundamentals:
- Real-world usage of HTML, including semantic and meta tags.
- Building well-formed web pages and structuring content effectively.
- Creating and testing user input forms with advanced features and validation.
- Embedding multimedia elements like video, audio, and iframes.
- CSS Styling:
- Moving beyond basic styling to create complex layouts using grids and flexboxes.
- Mastering CSS selectors and combinations for precise element targeting.
- Implementing pseudo-classes to enhance interactivity.
- Adding visual effects with CSS animations and transformations.
- Debugging and Assessment:
- Utilizing browser developer tools and UI testing for efficient debugging.
- Building a complete homepage for a fictional company as a graded assessment.
- Providing and receiving peer feedback to expand your learning experience.
Learning Approach:
- Engaging videos: Benefit from clear and informative video lectures.
- Supplemental resources: Solidify your understanding with course readings and exercises.
- Self-assessment quizzes: Regularly gauge your progress through interactive quizzes.
- Interactive community: Engage with fellow learners through discussion prompts and build your network.
Start your journey towards becoming a web developer today!
Hello and welcome to this
course on HTML and CSS. Every day when you
browse the Internet, you’re interacting with
HTML and CSS code. By now, you probably know a little bit about
how that works. If you’re taking this course, you want to find out
even more. That’s great. There will be a short
overview of HTML and CSS just after
this introduction. But first, let’s briefly go through what you’ll be
doing in this course. You’ll start off by learning how HTML is used in the real-world. This includes learning about semantic and Meta tags
and the importance of having a structured
approach so that you can create well-formed
web pages. Next up are user
input and forms. In this part of the course, you will create and test
a form by yourself. You will learn about
advanced input types, how to validate input, and provide feedback to improve the user experience of a form. But what would the
web be without media? The next HTML section will focus on bringing websites to life with media elements. You will learn how to embed video and audio players
and even iframes. Following the module about HTML, is when all about CSS. This part of the course will
go beyond basic styling. You will learn how to create layouts with grids
and flex boxes. You will also learn about CSS
selectors and how you can combine them to refine the styling of elements
on your web pages. Not only that, but you’ll
also learn how to use pseudo-class
selectors to improve the interactivity of a web page. But there’s even more. You will learn how
to add effects on web pages using purely CSS and you will cover basic transform and
transition animations, as well as more advanced
animations using key frames. Next, you will learn how to use browser developer tools and UI testing to debug
HTML and CSS code. The final part of the module is about the graded assessment. For this assessment, you
will build a homepage for a fictional
company and you’ll get an opportunity to review
your classmates projects as well since this is a
peer graded assignment. There are many videos
in the course that will gradually guide you towards your goal of becoming
a developer. Watch, pause, rewind, and re-watch the videos until you are confident
in your skills. Then consolidate your knowledge by consulting the
course readings and putting your skills into practice during the
course exercises. Along the way, you’ll
encounter several knowledge quizzes where you can
self check your progress. Remember, you’re not alone in considering a career
as a developer, which is why you’ll also
work with course discussion prompts that help you to
connect with your classmates. It’s a great way to
share knowledge, discuss difficulties, and grow a network of contacts in
the web development world. You have probably encountered a few new words and technical
terms in this video. Don’t worry if you don’t fully understand all these
terms right now. Everything will
become clearer soon. After all, this is part of the reason why you’re
taking this course.
Video: How are HTML and CSS used in the real world?
Demystifying Web Development: HTML, CSS, and Beyond
This text explains the fundamental building blocks of the web: HTML and CSS.
Key Points:
- HTML:
- The foundational language for creating web pages, dating back to 1990.
- Used to structure content and display basic text and images.
- Recently enhanced for better multimedia support, responsive design, and user interaction.
- CSS:
- A stylesheet language that controls the visual presentation of an HTML document.
- Separates content (HTML) from styling (CSS) for easier maintenance.
- Offers features like controlling color, size, layout, and animations.
- Recently updated with media queries, box sizing, and animation capabilities.
Together, HTML and CSS:
- Enable website adaptability across various devices (computers, phones, tablets, etc.).
- Allow web pages to go beyond traditional browsers, appearing on game consoles and smart TVs.
Overall, this combination empowers developers to create visually appealing and user-friendly web experiences.
The combination of HTML and CSS has meant that web browsing can be done on a variety of devices and not just computers and phones. Which of the following statements about CSS are true? Select all that apply.
CSS gives you control over spacing and positioning of content on a web page.
That’s correct! It also gives you control over color, size and fonts.
CSS describes the look and layout of a document written in HTML.
That’s correct! CSS describes the look and layout of a document written in HTML.
You can change a web page’s appearance with CSS without editing its HTML.
That’s correct! This is possible because there is a separation between content and style in CSS.
The average person doesn’t know much about what happens behind the scenes when they browse the Internet on their
phone or computer. But as an aspiring developer, you are aware of how the
content on screen is controlled by HTML and CSS. By now you know that HTML is a markup language used
to create webpages. In fact, it’s the most basic
and fundamental language for creating webpages. Together with CSS, it has helped the web browser expand beyond
just desktop computers. HTML has been around since 1990, and it was originally
designed to provide a way for people to share information
over the Internet. HTML webpages used to only
show basic images and text. The websites you browse
today are very different. This is because HTML
can do much more than just defining how content is
displayed in the browser. HTML is great, but
together with CSS, it can do so much more. CSS is a stylesheet
language that is used to describe the look and layout of a document written in HTML. While CSS is not a
programming language, it does allow for some
programming like features, such as variables
and nested rules. What it does is gives
you control over color, size, spacing, fonts,
positioning, and more. One of the fundamental
principles of CSS is the separation
of content and style. That means you can change a webpages appearance without editing its underlying HTML. W3C, the organization responsible for standards
for the worldwide web, manages both HTML and
CSS specifications. They continually improve
their capabilities to ensure that they are always oriented towards current requirements. Many new features were added
to the current version of HTML that make it easier to
use than previous versions. These are better support for multimedia content such
as audio and video, improved support for responsive
design such as adopting the webpage layout depending on the device the
webpage is viewed on, new form input types such as
sliders and range inputs, date and color pickers, new form validation features, and new ways to work with texts such as spell
checking and text editing. Some major additions
released for CSS in 2011 ensure that CSS can style and control a
website regardless of the media content or the device used for
viewing the page. The additions to the current
version are; media queries, which allow for different
styles to be applied depending on the device being
used; box sizing, which allows developers
to specify how they want their content
to be sized and padded; multiple backgrounds,
which means you can specify multiple background
images for an element; border images, which allow developers to
specify an image as a border instead of
a solid color or style; text shadows, which means you can
add shadows behind text for a more
three-dimensional look; and transformations
and transitions, which allow developers to
animate elements on a webpage. In essence, the combination
of HTML and CSS allows websites to adapt
their design and layout based on the devices
on which they’re viewed. While this feature was
initially used to support mobile devices like cell
phones and tablets, the usage of HTML
and CSS has grown beyond the traditional
web browser and webpages. Today, webpages can be viewed not only on
computers, cell phones, and tablets, but also on video game consoles
and even smart TVs. The web browser has truly expanded beyond traditional
desktop devices, and it’s all thanks to the
combination of HTML and CSS.
Video: Recap: What you know about HTML and CSS
Refresher on HTML and CSS Fundamentals
This summary revisits the basics of HTML and CSS, providing a refresher for those with some prior knowledge or introducing the concepts to beginners.
HTML (Hypertext Markup Language):
- Function: Defines the structure and content of a webpage.
- Structure: Uses elements with opening and closing tags (e.g.,
<p>
,</p>
) to create different sections and display content. - Capabilities:
- Incorporate images, tables, and forms.
- Build accessible websites for users with disabilities.
- Interact with JavaScript through the Document Object Model (DOM).
CSS (Cascading Style Sheets):
- Function: Controls the visual presentation of a webpage.
- Analogy: Like paint and styling for an HTML structure (the building).
- Capabilities:
- Style individual elements within an HTML document.
- Create appealing layouts using the box model.
- Arrange page elements through normal document flow.
Next Steps:
Dive deeper into learning more about HTML and CSS.
HTML is foundational to websites and there is a lot that you can do with it. Which of the following are you able to do with HTML? Check all that apply.
You can build forms with HTML.
That’s correct! You can build forms with a wide range of inputs.
You can display data in tables with HTML.
That’s correct! HTML enables you to display data in tables.
You can add images to a web page with HTML.
That’s correct! HTML enables you to add images to a web page.
Perhaps you know a little about HTML and CSS from
another course you did, or perhaps you don’t
know much at all. Either way, a quick
summary will be useful. So let’s explore some basic HTML and CSS principles
and practices. HTML stands for Hypertext
Markup Language. But what does that mean? Hypertext is text which
contains links to other text. Markup refers to tags and elements used within a document. HTML elements with their
opening and closing tags in angle brackets make
up an HTML document. These elements form
the structure of a webpage and describe what to display to
the web browser. When it comes to HTML, it’s important to know about the purpose of HTML
in the web browser. The use of HTML tags
and correct syntax, and how HTML elements are
used in a web document. But what can you do with HTML? You can add images to a
web page with HTML code. You can use it to
display data in tables, and you can build forms with
a wide range of inputs. Also, using the
correct HTML structure and appropriate elements as a foundation is
an essential part of building accessible websites. HTML can assist in ensuring web accessibility
by supporting the technology people
with disabilities use to interact with and
understand websites. Another important concept to know about when
you’re talking about HTML is the Document
Object Model or DOM. Users need to be able to interact with elements
on a web page. This means that HTML
document must be represented in a way that JavaScript code can
query and update it. That’s the function of the DOM. It’s a model of the
objects in your HTML file. Web developers
interact with the DOM through JavaScript
to update content, set up events and
animate HTML elements. Now that you’ve covered
the basics of HTML, let’s move on to CSS or
Cascading Style Sheets. If HTML is the frame and
structure of a building, then CSS is the paint, wallpaper, fixtures,
and overall style. CSS tells the web browser how to display HTML elements on screen. You use CSS to style elements
within an HTML document, create an appealing layout for your webpage using
the box model, and arrange page elements
using normal document flow. That was your HTML
and CSS refresher. Now get ready to
dive deeper into learning more about
these two topics.
Semantic and Meta Tags
Video: Semantic tags and why we need them
How to Use Semantic HTML for Meaningful Web Pages
- Semantic HTML tags give meaning to content. This is like adding numbers to elevator buttons, helping users and search engines understand the purpose of elements on your page.
- Basic Semantic Tags: Headings (<h1>), lists (<ul>, <ol>), and others are fundamental.
- Key Structural Semantic Tags:
- header: Top of the page, often includes logo and navigation.
- nav: Contains the site’s primary navigation links.
- main: Houses the core content of the page.
- article: Used for self-contained content pieces (blog posts, forum threads, etc.).
- section: Divides content within articles or the main page into logical sections.
- footer: Located at the bottom, often has contact information or additional links.
Why Semantic HTML Matters:
- Accessibility: Screen readers and other assistive technologies rely on semantic tags to make content understandable for those with disabilities.
- SEO: Search engines use semantic structure to better grasp your page’s content and its relevance to search queries.
Example Structure: A blog post might have a header with logo and navigation, a main area containing the article (which itself might have a header, sections, etc.), and a footer with contact information.
What is Semantic HTML?
- Semantic HTML uses specific tags to describe the meaning and purpose of content on your web pages, rather than just how it should look.
- Think of it like labeling items in a well-organized kitchen. Instead of just having containers, you label them “flour,” “sugar,” etc. Semantic HTML does the same for your web page elements.
Why Semantic HTML Matters
- Accessibility: Screen readers and other assistive technologies rely on semantic tags to interpret and convey the structure of your page to users with disabilities.
- SEO: Search engines like Google analyze semantic markup to better understand the content and relevance of your pages. This can potentially improve your search rankings.
- Maintainability: Semantic code is easier to read, understand, and update, making your website more maintainable for you and other developers.
Key Semantic HTML Tags
Here’s a breakdown of some of the most important semantic tags and when to use them:
- Structural Tags
<header>
: Typically used for the top section of your page, including logos, titles, and navigation.<nav>
: Defines the main navigation links on your site.<main>
: Encloses the primary content of your page.<article>
: Represents a self-contained piece of content, like a blog post, news article, or product listing.<section>
: Divides content into thematic sections within an article or the main page.<footer>
: Placed at the bottom of the page, often containing copyright information, contact details, or secondary links.
- Textual Tags
<h1>
–<h6>
: Heading tags, with<h1>
being the most important and<h6>
the least. Use these to structure your content hierarchically.<p>
: Represents a paragraph of text.<em>
: Emphasizes text.<strong>
: Marks text as strongly important.<ul>
: Defines an unordered list (bullet points).<ol>
: Defines an ordered list (numbered).<li>
: Represents a list item within a<ul>
or<ol>
.
Tutorial: Building a Semantic Web Page
Basic Structure: Start with the core HTML template:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document Title</title>
</head>
<body>
<header>
</header>
<main>
</main>
<footer>
</footer>
</body>
</html>
Add a Blog Post: Let’s create a sample blog post using semantic elements:
<main>
<article>
<header>
<h1>The Importance of Semantic HTML</h1>
<p>By Jane Doe, August 15th, 2023</p>
</header>
<section>
<h2>Introduction</h2>
<p> ... </p>
</section>
<section>
<h2>Benefits of Semantic HTML</h2>
<p> ... </p>
</section>
</article>
</main>
Tips
- Nest elements carefully: Semantic tags can be nested within each other to reflect the hierarchical structure of your content.
- Don’t overuse
<div>
: While the<div>
tag is still useful, try to favor descriptive semantic tags whenever possible. - Validate your HTML: Use an HTML validator (https://validator.w3.org/) to check for errors and ensure your markup is correct.
By using semantic HTML, you’ll create web pages that are more accessible, search engine friendly, and easier to maintain – benefiting both users and your development process!
Semantic tags describe the meaning of a web page and they help search engines and accessibility software like screen readers to understand the contents of a page. Which of the following statements are true? Choose all that apply.
Basic HTML tags like the heading and list tags can be used to describe content.
That’s correct! For example, a heading tag like h1 describes that the content is a heading.
The article element is used for complete, self-contained compositions on a web page.
That’s correct! Examples include a blog post, or an article published in an online magazine or newspaper.
The main navigation links of your website should be added inside the nav element.
That’s correct! The main links allow users to navigate between different parts of your web page.
By now you know that HTML describes
the content of a web page. But how do you describe
the meaning of a web page, to understand this in a real world
context think of buttons in an elevator. The vertical arrangement
of buttons isn’t enough for someone to understand their meaning. To convey the meaning or semantics
of the buttons numbers are added so that people know which button
will take them to which floor. When you write HTML it’s good practice
to semantically describe the content. This allows search engines and
accessibility software such as screen readers to understand
the contents of a page, fortunately you can do this by
using some basic HTML tags. For example using a heading tags such
as H1 describes that the content is a heading. Similarly the UL and
OL tags describe lists. However, there are many more semantic HTML
elements available to you as a developer. In this video I will share
a structured approach you can take to make sure that you
create a well formed web page. Let’s revisit the basic structure
of an HTML page which includes the head and body. Inside the body tag you can lay out
the website with very semantic tags to describe each of the sections. For a typical HTML page the structure
can be semantically described using the header, main and
footer semantic HTML tags. For example, suppose you lay out your page
with a header section that contains some company logo and navigation links. Then a main section contains sections and
articles. Finally a footer section contains contact
information and social media links. The main navigation section of your
web page can also be described semantically using the Nav tag. Depending on how web pages designed
the Nav element is often placed after the header element and
the header element is used for logos. The main links of your website
are then added inside the Nav element. It is common practice for developers to specify their links as
an unordered list inside the Nav element. Next is the main content of a web page. The two key semantic elements for
your main content are the article and section elements. First let’s examine the article element. The HTML specification
states that according to the World Wide Web Consortium’s website, the article element indicates
content which represents a complete. Or self contained composition in
a document page application or site that is independently distributable. That’s quite a mouthful. It may help to think of
a page in a newspaper. There are many articles on the page and you can cut out the individual
articles with scissors if you want to. The articles you can remove
are the article element. Examples of this include a forum post,
a magazine or a newspaper article, a blog entry, a user submitted comment,
an interactive widget or gadget or
any other independent item of content. Let’s examine how the article
element is used say you are developing a blog
about your summer holiday. It’s good practice to contain the blog
post content inside of the article element because it’s a complete
self-contained composition on a web page. You should place the article
element within your main element. Then you add your regular heading and
paragraph tags inside the article element. The reason for doing it this way is
because the main element semantically represents the main content of the page. And inside of it there can be
multiple article elements for something like a blog post list. At the end of your document
is the footer element. This might contain additional
navigation links or other content. It is important to note that semantic
elements are not limited to this structure. Since their purpose is to describe
the semantics of the content, the elements can be nested
inside of each other. If it accurately describes the content, let’s update the previous example
to use a nested semantic structure. You add a header element
to the article element, inside the header element at the heading
element with the blog title and a paragraph element describing
the date and author of the blog post. Inside the main element at
the content of the blog post. That’s it,
let’s examine the section element. You can add a section element to
semantically define individual sections of the article. It is important to note that sections
should contain heading elements to semantically describe the section. It is also possible to use section
elements to describe different sections of your webpage, the section element
doesn’t require the article element. It all depends on how you want to
semantically describe your page. And now you know how to semantically
describe the contents of a web page, your web pages more accessible
because the content is semantically described to add meaning. Now, search engines and accessibility
software can easily understand the contents of your well formed web page.
Reading: Semantic HTML cheat sheet
Reading
There are hundreds of semantic tags available to help describe the meaning of your HTML documents. Below is a cheat sheet with some of the most common ones you’ll use in this course and in your development career.
Sectioning tags
Use the following tags to organize your HTML document into structured sections.
<header>
The header of a content section or the web page. The web page header often contains the website branding or logo.
<nav>
The navigation links of a section or the web page.
<footer>
The footer of a content section or the web page. On a web page, it often contains secondary links, the copyright notice, privacy policy and cookie policy links.
<main>
Specifies the main content of a section or the web page.
<aside>
A secondary set of content that is not required to understand the main content.
<article>
An independent, self-contained block of content such as a blog post or product.
<section>
A standalone section of the document that is often used within the body and article elements.
<details>
A collapsed section of content that can be expanded if the user wishes to view it.
<summary>
Specifies the summary or caption of a <details> element.
<h1><h2><h3><h4><h5><h6>
Headings on the web page. <h1> indicates the most important heading whereas <h6> indicates the least important.
Content tags
<blockquote>
Used to describe a quotation.
<dd>
Used to define a description for the preceding <dt> element.
<dl>
Used to define a description list.
<dt>
Used to describe terms inside <dl> elements.
<figcaption>
Defines a caption for a photo image.
<figure>
Applies markup to a photo image.
<hr>
Adds a horizontal line to the parent element.
<li>
Used to define an item within a list.
<menu>
A semantic alternative to <ul> tag.
<ol>
Defines an ordered list.
<p>
Defines a paragraph.
<pre>
Used to represent preformatted text. Typically rendered in the web browser using a monospace font.
<ul>
Unordered list
Inline tags
<a>
An anchor link to another HTML document.
<abbr>
Specifies that the containing text is an abbreviation or acronym.
<b>
Bolds the containing text. When used to indicate importance use <strong> instead.
<br>
A line break. Moves the subsequent text to a new line.
<cite>
Defines the title of creative work (for example a book, poem, song, movie, painting or sculpture). The text in the <cite> element is usually rendered in italics.
<code>
Indicates that the containing text is a block of computer code.
<data>
Indicates machine-readable data.
<em>
Emphasizes the containing text.
<i>
The containing text is displayed in italics. Used to indicate idiomatic text or technical terms.
<mark>
The containing text should be marked or highlighted.
<q>
The containing text is a short quotation.
<s>
Displays the containing text with a strikethrough or line through it.
<samp>
The containing text represents a sample.
<small>
Used to represent small text, such as copyright and legal text.
<span>
A generic element for grouping content for CSS styling.
<strong>
Displays the containing text in bold. Used to indicate importance.
<sub>
The containing text is subscript text, displayed with a lowered baseline.
<sup>
The containing text is superscript text, displayed with a raised baseline.
<time>
A semantic tag used to display both dates and times.
<u>
Displays the containing text with a solid underline.
<var>
The containing text is a variable in a mathematical expression.
Embedded content and media tags
<audio>
Used to embed audio in web pages.
<canvas>
Used to render 2D and 3D graphics on web pages.
<embed>
Used as a containing element for external content provided by an external application such as a media player or plug-in application.
<iframe>
Used to embed a nested web page.
<img>
Embeds an image on a web page.
<object>
Similar to <embed> but the content is provided by a web browser plug-in.
<picture>
An element that contains one <img> element and one or more <source> elements to offer alternative images for different displays/devices.
<video>
Embeds a video on a web page.
<source>
Specifies media resources for <picture>, <audio> and<video> elements.
<svg>
Used to define Scalable Vector Graphics within a web page.
Table tags
<table>
Defines a table element to display table data within a web page.
<thead>
Represents the header content of a table. Typically contains one <tr> element.
<tbody>
Represents the main content of a table. Contains one or more <tr>elements.
<tfoot>
Represents the footer content of a table. Typically contains one <tr> element.
<tr>
Represents a row in a table. Contains one or more <td> elements when used within <tbody> or <tfoot>. When used within <thead>, contains one or more <th> elements.
<td>
Represents a cell in a table. Contains the text content of the cell.
<th>
Defines a header cell of a table. Contains the text content of the header.
<caption>
Defines the caption of a table element.
<colgroup>
Defines a semantic group of one or more columns in a table for formatting.
<col>
Defines a semantic column in a table.
Video: Semantic tags in action
Key Points
- Semantic Focus: The developer prioritized using semantic HTML tags to make the blog easily understood by search engines and accessible to users with disabilities.
- Structural Elements:
- header: Contains the restaurant logo.
- nav: Houses the site’s navigation links (index, location, blog).
- main: Holds the primary blog content.
- footer: Includes the copyright notice.
Blog Content
- Heading: An
<h1>
tag is used for the main blog page title. - Blog Posts: Each post is contained within an
<article>
element.- Individual Post Titles:
<h2>
tags mark the titles of each blog post. - Post Content: Paragraphs (
<p>
) hold the text of each blog post.
- Individual Post Titles:
Benefits
- Accessibility: The semantic structure makes the blog easily navigable for those using screen readers or other assistive technologies.
- SEO: Search engines will better understand the content of the blog page, potentially boosting its visibility in search results.
Is the following statement true or false? If you want to create an unordered list you should use the li tag.
False
That’s correct! For an unordered list you use the ul tag. The li tag is list item.
The Little Lemon Restaurant has asked me
to add a new blog page to their website. They’ve told me that the page will
contain several blog posts, and that it must use semantic html so
that search engines and accessibility software can understand
the semantics of the page. I’ve set up my basic html document
structure in a file named blog.html. I’ll start off by adding my
basic semantic structure. First I add the header element. Followed by the nav element, Followed by the main element. Followed by the footer element. Remember this structure describes
the semantics of this html document. Specifically the header element will be
used to display the Little Lemon logo, and the nav element will be used to describe
the navigational structure of the website. The main element will feature
the main content of the web page, and the footer will be used to
display copyright information. When a search engine or accessibility
software reads this document, the semantic tags will help
the software understand the purpose and meaning of different
sections of the document. I will now add the details
to each element. Inside the header element, I add
the Little Lemon logo using the image tag. Inside the nav element, I add the navigation links in an a ordered
list element using the ul tag. I then add three list item
elements using the li tag. Inside the list items, I add the hyperlinks for index.html, location.html and blog.html using the anchor tag. In the main element,
I add an h1 tag for the blog heading. The restaurant told me that there will
be two blog posts for their website. So I add two article elements
after the h1 element. Inside the first article element, I add
an h2 tag for the title of the blog post. The title is 20% off this weekend. I then add a paragraph
element below the title which contains the blog post text. Inside the second article element,
I add an h2 tag for the title which is our new menu. Again I add a paragraph element below the
title which contains the blog post text. Finally, I add a paragraph
element to the footer element. In this paragraph element,
I add the copyright notice. The blog pages now semantically
described through the html document. I now save the file by pressing
Control and S or Command and S on Mac. I then right click the blog.html file and
select live preview to preview the file. The blog page looks good and
all thanks to proper semantic design that ensures accessibility and
search engine optimization. I’m sure that the Little Lemon Restaurant
will get lots of business through their blog, and their customers with disabilities will be
able to access the blog with no problems
Practice Quiz: Knowledge check: Practice using semantic tags
What is the purpose of Semantic HTML tags?
To describe the meaning of the HTML document
That’s correct! Semantic tags describe the meaning and intent of the HTML document.
What is the impact of using semantic tags in your HTML document? Select all that apply.
It allows accessibility software to understand the HTML document
That’s correct! The semantic tags allow accessibility software such as screen readers to understand the document.
It allows search engines to understand the HTML document
That’s correct! The semantic tags allow search engines to understand the HTML document.
What type of content is the <article> semantic HTML element appropriate for? Select all that apply.
News article
That’s correct! A news article is a self-contained block of information suitable for the <article> semantic tag.
Forum post
That’s correct! A forum post is a self-contained block of information suitable for the <article> semantic tag.
Blog post
That’s correct! A blog post is a self-contained block of information suitable for the <article> semantic tag.
Which of the following elements is most suitable for describing the navigation section of a webpage?
<nav>
That’s correct! <nav> is most suited for describing the navigation section.
You need to add a copyright notice to the bottom of a web page. Which of the following semantic tags is most suitable to use?
<footer>
That’s correct! <footer> should be used for the copyright notice as the notice is not the main focus of the content.
You need to indicate that a section of text in a <p> element is important. Which of the following semantic tags should you use?
<strong>
That’s correct! <strong> indicates that a section of text is important.
You need to display a list of descriptions on a web page. Which of the following tags are best-suited semantically?
<dl>
That’s correct! <dl> semantically describes a description list.
Video: Metadata
How Search Engines Work
- Search engines analyze websites to determine their relevance to a user’s search query. This involves:
- Crawling the website’s HTML and media content
- Following links to explore the entire site
- Each search engine has a unique algorithm for ranking websites, meaning your site might rank differently on different search engines.
Meta Tags and SEO
- Meta tags provide data about your webpage, but don’t display in the browser.
- Key meta tags for SEO include:
- Author: Identifies the page’s creator.
- Description: Summarizes the page’s content, often used by search engines in search result descriptions.
- Keywords: While no longer heavily relied upon, some search engines still consider these. Avoid using them to manipulate rankings.
- Robots: Can instruct search engine bots whether to index your page and follow its links. Use with caution, as some bots ignore these settings.
- Viewport: Critical for responsive design, ensuring proper display on mobile devices. Search engines favor mobile-friendly sites.
Important Note: While meta tags help, they are just one part of a good SEO strategy. High-quality content, site structure, and other factors all play a role in how well your website ranks.
You want to improve the SEO of a website. What metadata should you add to the head element of the website and why? Check all that apply.
Author metadata to inform search engines who the author of the web page is.
That’s right. Author metadata specifies the author of the web page.
Viewport data to help web browsers display websites at the appropriate scale on the device being used.
That’s right. Mobile devices will by default attempt to render a web page as if it is being viewed on a desktop. The solution is to define viewport metadata.
Description metadata to help search engines understand what the web page is about.
That’s right. The description metadata describes the content of the web page.
Robots metadata to improve how search engines analyze the website.
That’s right. The name “robots” comes from the automated software, often referred to as “bots”, that search engines use to analyze websites.
When was the last time
you used a search engine? Probably in the last few hours or minutes. Perhaps you just wanted to
quickly look something up or maybe you needed more in
depth information on a topic. Either way, the search engine you used
will have returned a list of results that were most relevant to
what you searched for. But how does a search
engine determine which web pages are most relevant in this video? You will learn how search
engines analyze web pages and how meta tags help provide information for
search engines. A major part of launching a website
is a process called search engine optimization or SEO. This process involves making improvements
to a website’s content semantics and delivery to improve its
ranking in search results. You might be wondering what exactly
does a search engine do when it analyzes a web page? Well when a search engine
visits your website, it analyzes the html document and
media content. If it finds a link to
another html document, it follows the link to that document and continues following links until it is
finished analyzing the entire website. Based on the results of the analysis and
the content on your website, the search engine will rank
the website for various search terms. So while your website might be the number
one result for one search term, it could rank very low for another. Every search engine has its own
algorithm for ranking websites. And while it’s not disclosed how
the ranks are determined, there are many best practices you can follow to
influence how search engines analyze and rank your website. But for now let’s just focus on how
meta tags influence website ranking. Meta tags define metadata
about a web page. What is metadata? You ask? It’s data about other data which in
this case is data about the web page. Meta tags are added inside the head
element of your html document and as you know, nothing inside the head
element is displayed in the web browser. In other words, meta tags are unseen
elements within the browser. Note that there is no closing tag for
the meta tag. The meta element has two attributes,
name and content. The name attribute specifies
the name of the metadata and the content attribute specifies
the value of the metadata. Let’s examine some examples of metadata. The author metadata specifies
the author of the web page. The name attribute is author and
the content attribute is the person and company who are the author
of the web page. The description metadata describes
the content of the web page. This is often used by search engines
as descriptive text in search results. The name attribute is
set to description and the content attribute is
the descriptive text. The keywords metadata was previously
used to provide search keywords for search engines. However, this led to a lot of websites
using the keywords metadata to manipulate search rankings. One of the major search engines
now ignores this metadata and another uses keywords metadata as
a spam indicator because of this, it’s recommended not to include
this metadata in modern web pages. Another type of metadata
is the robot’s metadata and it tells search engines if and
how they should analyze your web page. The name robots comes from the automated
software often referred to as bots, that search engines used
to analyze websites. The content attribute for
Robots has four possible values. Index tells the bot to analyze the page. Follow tells the bot to also
visit all links on the web page. No index tells the bot
not to analyze the page. Some bots will ignore this so it’s best not to rely on this to stop
bots from analyzing your page and no follow tells the bot not to
visit links on the web page. Again, some bots will ignore this value so
it’s best not to rely on it. Finally, there’s the view ports metadata. The view port metadata is important
when designing responsive web pages. Why you might ask because when
a web pages viewed on a phone or tablet, the device will by default
attempt to render the web page as if it is being viewed on a desktop. This results in a poor browsing
experience for the user. The solution is to define
view ports metadata. There are many values available for
view ports metadata. The most used value for the mobile
experiences is to set the width to device dash with and the initial scale to 1.0, you can learn more about view
ports in the additional reading. It’s important to note that view port
metadata does not solve all the issues with browsing websites on mobile devices. The other part of the solution
is responsive web design. But we were talking about search
engine optimization, right? View port metadata is important for
the user experience and it’s also important for
search engine optimization. This is because many search engines now
include websites mobile experience as a part of their ranking algorithms, there
is more metadata that you can define on you web page to specifically improve
its presence on social media. But that’s for later video. For now it’s important to know that
author description, keywords, robots and view ports metadata all play a role in the
search engine optimization of web pages.
Reading: Metadata cheat sheet
Reading
HTML <meta> tags
Earlier in the course, you learned about meta tags and how you can leverage them to convey information to search engines to better categorize your pages. We recommend that you keep this cheat sheet handy when building your web applications. The structure of a meta tag is as follows.
Name
The name of the property can be anything you like, although browsers usually expect a value they understand and can take an action upon. An example would be <meta name="author" content="name"> to state the author of the page.
Content
The content field specifies the property's value. For example, you can use <meta name="language" content="english">, to specify the language of the webpage to search engines.
Charset
The charset is a special field that lets you specify the character encoding used for the page so that the browser can display it properly. The most frequently used is utf-8, and you would add it to your HTML header as follows: <meta charset="UTF-8">
HTTP-equiv
This field stands for HTTP equivalent, and it’s used to simulate HTTP response headers. This is rare to see, and it’s recommended to use HTTP headers over HTML http-equiv meta tags. For example, the next tag would instruct the browser to refresh the page every 30 minutes: <meta http-equiv="refresh" content="30">
Basic meta tags (meta tags For SEO)
<meta name="description"/> provides a brief description of the web page
<meta name=”title”/> specifies the title of the web page
<meta name="author" content="name"> specifies the author of the web page
<meta name="language" content="english"> specifies the language of the web page
<meta name="robots" content="index,follow" /> tells search engines how to crawl or index a certain page
<meta name="google"/> tells Google not to show the sitelinks search box for your page when showing search results
<meta name="googlebot" content=”notranslate” /> tells Google you don’t want to provide an automatic translation for your page if the user uses a different language
<meta name="revised" content="Sunday, July 18th, 2010, 5:15 pm" /> specifies the last modified date and time on which you have made certain changes
<meta name="rating" content="safe for kids"> specifies the expected audience for your page
<meta name="copyright" content="Copyright 2022"> specifies a Copyright
<meta http-equiv="..."/> tags
<meta http-equiv="content-type" content="text/html"> specifies the format of the document returned by the server
<meta http-equiv="default-style"/> specifies the format of the styling document
<meta http-equiv="refresh"/> specifies the duration of the page before it’s considered stale
<meta http-equiv=”Content-language”/> specifies the language of the page
<meta http-equiv="Cache-Control" content="no-cache"> instructs the browser how to cache your page
Responsive design/mobile meta tags
<meta name="format-detection" content="telephone=yes"/> indicates that telephone numbers should appear as hypertext links that can be clicked to make a phone call
<meta name="HandheldFriendly" content="true"/> specifies that the page can be properly visualized on mobile devices
<meta name="viewport" content="width=device-width, initial-scale=1.0"/> specifies the area of the window in which web content can be seen
Video: Bare bones layout
Purpose of the Template
- Provides a pre-structured HTML file with key elements in place, saving you time when starting new web projects.
Template Structure
- DOCTYPE & HTML: Basic declarations for a valid HTML document.
- Head:
- Title, Metadata: Update these for SEO and social media sharing.
- Icon Links (if needed)
- Linked CSS file (
styles.css
)
- Body
- Semantic structure:
<header>
,<nav>
,<main>
,<footer>
- Linked JavaScript file (
script.js
)
- Semantic structure:
Benefits of Using the Template
- Faster Development: Start building content immediately instead of writing boilerplate code.
- Semantic Best Practices: Encourages using meaningful HTML tags for better accessibility and SEO.
- Organization: Dedicated folders for CSS (
styles.css
) and JavaScript (script.js
) keep your project tidy.
How to Use
- Save a copy of the template locally.
- Update metadata (title, description, etc.).
- Add your content within the semantic HTML structure.
- Write your styles in
styles.css
and JavaScript inscript.js
When adding a new CSS and a new JavaScript file to the template web page, what needs to be done? Check all that apply.
- Add the JavaScript file to the js folder
- Add a script element to reference the JS file
- Add the CSS file to the css folder
- Add a link element to reference the CSS file
An important part of being a developer is not just
the tools you use, such as your integrated
development environment, but also the repository
of knowledge and code templates you
build up over time. In this video, I’m going to introduce you
to one of these templates, which will help you get set up quickly for building webpages. Let’s open Visual Studio Code to go through the
templates step-by-step. In the folder, we
have index.html along with the JS folder
and a CSS folder. Inside the JS folder, there’s a file named script.js. There is no content
in this file. It is added to this
folder so that you can easily add JavaScript
code to the webpage. I recommend that you add any other JavaScript
files to this folder too. Next, I’ll open the CSS folder. In the folder there’s a
file named styles.css. Again, there is no
content in this file, but it is here so
that you can easily add CSS rules to the webpage. Again, it’s best if you add any other CSS files
also to this folder. I go back to my
template folder and open it in Visual Studio Code. I open the index.html file. The file has a semantic HTML
document structure set up. At the top, there is
the DOCTYPE declaration followed by the
HTML root element. Inside the root element, there are the head and body
elements in the head element. The title and meta tags are already optimized
for search engines. I recommend that you
update the title along with the description
and author meta tags. Below, are the Meta tags for
the Open Graph Protocol. Don’t worry about the
details of these tags just yet as you learn about
them in a later video. For now, the main
thing to know is that if you plan on sharing the
webpage on social media, you should remember to uncomment this HTML section and update
the content attributes. The next block of commented
out code is for icons. If you want to show an icon in the web browser tab
for your website, you can update the href attributes here to
point to your icon. Remember it you always
link elements for the CSS style sheet to the last section of
the head element. To speed things up for you, there is a link already
set up to reference the styles.css file in
the CSS folder. By now you can probably see
how useful this template is. Let’s continue to
the body element. The body element
already contains a basic semantic structure. This includes the header element for your website title or logo, the nav element for your
website navigation, the main element for
your main content, and the footer element
for any copyright notices or links to secondary webpages. Below the footer element, you add script elements
for JavaScript files. To make your life easy, a script element is already
set up to reference the script.js file in the JS folder. With this template,
you’ll be able to quickly start building
out webpages. It’s worth keeping a
copy of this template on your local machine to use and reference in
future projects. In this video, you’ve
been introduced to a semantic HTML
template that you can use for building webpages. Good luck.
Practice Quiz: Knowledge check: Metadata
What are some of the main characteristics of meta tags? Select all that apply.
They are very important for SEO
Correct! They define and influence how search engines rank your pages.
They define metadata about an HTML document, namely information about data
Correct! They are contextual information for browsers.
They don’t have a visual representation in your pages
Correct! They will not be displayed on the page.
What are some of the most important Meta tags you should use for good SEO? Select all that apply.
Description
Correct! Although it is not a ranking factor, search engines tend to display descriptions as accompanied snippets.
Title
Correct! Search engines use them as clickable headlines and titles are given high weight in the ranking factor.
Image alt attributes
Correct! They help search engines understand what the images are about.
Which meta tag is used to specify the character encoding for the HTML document?
charset
That’s correct! You should use charset to tell the browser the encoding used in your HTML pages, like UTF-8, for example.
Which meta tag and properties do you need to set to make your pages responsive in desktop and mobile viewports?
<meta name=”viewport” content=”width=device-width, initial-scale=1” />
That’s correct! It’ll establish a 1:1 relationship between CSS pixels and device-independent pixels, taking screen orientation into account.
How do you tell Google you don’t want to provide an automatic translation for your page if the user uses a different language?
<meta name=”googlebot” content=”notranslate” />
That’s correct! This is how you instruct Google to skip an automatic translation.
Which of the following statements are true about HTTP-equiv tags? Select all that apply.
They can simulate HTTP response headers
Correct! The server can attach http-equiv meta tags for additional instructions to the browser.
They are useful if you don’t have access to the server configuration
Correct! This is true if you are using a shared hosting where it’s up to the hosting company how to respond to the requests.
Reading: Layout design
Reading
Video: UX with meta tags
Social Media Previews: The Problem
- When sharing links, it’s useful to see a preview of what the linked website is about.
- Facebook’s growth meant a huge volume of links, making previews essential for good user experience.
The Open Graph Protocol
- What: A set of metadata rules that tell social networks how to display previews of your web pages.
- How: Uses special
<meta>
tags within the<head>
of your HTML. - Key Difference: These meta tags use the
property
attribute instead of thename
attribute.
Required Open Graph Properties
- og:title: The title displayed in the preview.
- og:type: Content type: website, article, video, etc.
- og:url: The permanent URL for the specific page.
- og:image: The image for the preview.
Optional (But Useful) Properties
- og:description: A brief description of the content.
- og:locale: Language and region (e.g., ‘en_US’)
- og:site_name: The name of the larger website the page is part of.
The Result
When you share a page with the right Open Graph Protocol meta tags, social media platforms can generate informative and engaging link previews!
Frontend developers use the Open Graph Protocol to improve the user experience of shared links because it helps social media platforms create a preview of the shared web page.
Yes
That’s correct, the Open Graph Protocol is a set of metadata rules that allows web pages to describe themselves to social networks. Social media platforms use these meta tags to create a preview of the shared web page.
Social networks are a great tool to share content with
friends and family, and even with coworkers
and business partners. When you share a link, most social networks
generate a preview of the link to let users know what the linked
webpage is about. Now that you’re
learning more about front end web development, you’re probably wondering how social networks generate
these previews. In this video, you will
learn how Meta tags help webpages create previews
of other web pages. By using Meta tags to control what information is
displayed to users, you can get more clicks when
you share your websites. But the Meta tags web developers
use for this purpose are different from the traditional SEO Meta tags that you learned about earlier
in this lesson. Traditional SEO Meta tags are oriented towards search
results, not direct links. Facebook’s rapid growth
led to millions of people sharing thousands
of links every day. To improve the user experience, they had to find a way to
display information about a website before a user
clicks on the link. To address this challenge, Facebook established the
Open Graph Protocol in 2010. The Open Graph
Protocol is a set of Metadata rules that allow web pages to describe
themselves to social networks. There are many Metadata options available within the protocol, but before you learn about them, let’s first discuss how the Open Graph Protocol
Metadata is defined. Earlier in this lesson, you learned that Meta
tags are defined inside of the head element
of an HTML document. The Open Graph Protocol also uses Meta tags added
to the head element, but they are slightly different. Instead of the name attribute, the Open Graph Protocol uses the property attribute to
define the Metadata name. Then, like the
regular Meta tags, it uses the content attribute to define the Metadata value. Each property in the Open
Graph Protocol starts with og : as a convention to identify it as an Open Graph
Protocol related tag. The Open Graph Protocol
requires that you must always include four
properties on a webpage. These are title,
type, URL, and image. The title property defines
the title of the page, this is the text that will
appear in the preview. The type property defines
the type of content, such as website, video,
music, or article. Depending on the value
you specify as the type, other properties
may be required. You will learn about
these in a later video. The URL property defines
the permanent web address that the social network must
use for the specific page. The image property
defines a URL to an image that must display
when the website is shared. Together, these Open Graph
Protocol properties enables social media platforms to create a preview of the
shared web link. Say, you share a blog post. The title of the post
is the og:title, the blog post URL is the og:url, and the image that
displays is the og:image. There are several other
optional properties that you will learn
more about later. But let’s briefly
explore three of these. The description
property provides a description of the webpage. The locale property
describes the language and territory of the
webpage’s content. For example, en_US
specifies that the page is in English and the locale is the United States. The site name property
describes the name of the overall website that
the webpage belongs to. You’ve now learned how to use Metadata to describe
web pages so that social networks can improve user experience by
previewing shared content. Next time you share a
website on a social network, you can use what
you’ve learned about Open Graph Protocol properties
to generate more clicks.
Reading: Social media cards
Reading
Introduction
Before Facebook introduced the Open Graph Protocol (OGP), search engine web crawlers, including social media websites, used the internal heuristics of a website to make the best possible guess in terms of the title, description, and preview images to be used for the content.
This often led to social networks having difficulty interpreting the post or information shared in the URL provided. Even today, when you open a link for a website, the preview generated is often an out-of-scale or random image that is possibly embedded somewhere within the web page. This is where meta tags help the end-user take better control of their content.
Over the years, the successful implementation of OGP has led other social media giants, including sister companies owned by Meta, to adopt the protocol to improve the user experience. These platforms have their meta tags that prefix and replace ‘og’ that you have encountered earlier in the course.
Need for social media cards
With the number of users and the use of Internet marketing on the rise, user attention is the currency. It is said that a picture is worth a thousand words, and the internet is living proof of this: a caption and image can drive users toward or away from a website. The following image is an example of a social media card for this course:
The title and description shared with a URL should summarize the contents of a web page. Sometimes, it may refer to generic information about the entire website. For others, you may tailor the social media (SM) card for a specific page on a website that you’re sharing. The following image is an example of a social card for this course when shared on social media:
The type OGP tag
‘type’ is an important OGP tag in SM cards that helps describe the details of a link, like if it’s a book, an article, or a movie. It provides more detailed metadata for specific types. For example, in the case of the music type, you can add details for the song, album, duration, or any other information about the song. For a regular user scrolling through social media, the link provided with the image preview has only one chance and a moment’s attention to make a good impression. In such cases, the role of social media cards becomes very important.
Social media cards and SEO
Today’s internet is an interconnected graph that is internally a web of URL links, web crawlers, and search engine optimization tools. Together, a web page’s image and title are the store front to invite the user. But social media cards also play an important role in boosting the rankings for the web crawlers used by search engines. They provide the crawlers with the necessary information to build metadata that eventually helps rank websites. Additionally, it also helps track traffic to your website.
While it’s advised to stick to the required tags in social media cards, a developer can also use auxiliary tags that may be suitable. For example, the use of the video tag helps to play in line when displayed on social media websites like Meta.
Meta also has a dedicated page to assist developers that you can find in the additional resources for this section.
Conclusion
You should now be more familiar with social media cards, including their importance and benefits. Effective social media cards help to inform Internet users about your website and drive traffic towards it. The extra time a developer spends adding social media tags is worth the effort!
Practice Quiz: Knowledge check: Open Graph Protocol
How does the Open Graph Protocol (OGP) name the meta tags?
using property attribute
That’s right! Naming OGP meta tags inside the property attribute won’t enable social media to properly identify OGP properties.
Each property in the Open Graph Protocol starts with ‘ogp:’
False
That’s right! The property value starts with ‘og:’ instead of ‘ogp:’
Which property should be used to define a URL of an image that must display when the website is shared on social media?
og:image
That’s right! The image property declares the url of the image that must be shared.
Which property is used to define the language of the content being shared?
og:locale
That’s correct! The locale contains abbreviated information regarding the language.
The type property defines the type of the content. For example:
<meta property="og:type" content="website" />
Which property would mention the name of the website?
og:site_name
That’s right! The name of the website is mentioned through this property.
When sharing your blog post, which property would you use to provide the link to the actual post?
og:url
That’s right! The post url is defined with the og:url property.
Practice Quiz: Knowledge check: Semantic and meta tags
When setting up viewport metadata for mobile experiences, the ideal suggested value for ‘initial-scale’ is:
1
That’s correct! The most used viewport value for mobile experiences is to set the width to device-width and the initial-scale to 1.
True or false. The viewport metadata can impact Search Engines rankings.
True
That’s correct! The viewport metadata is important when designing responsive web pages because the mobile experience of users has an influence on SEO.
Which of the following meta tags are used for Search Engine Optimization?Select all that apply.
Viewport
That’s correct! viewport size is important for SEOs.
Author
That’s correct! Proper author tags are important for SEO.
Description
That’s correct! The description metadata describes the content of the web page and is often used as descriptive text in search results.
Which of the following are the required properties while making social media cards using OGP? Select all that apply.
type
That’s right! The Open Graph Protocol requires that you must always include the type property.
image
That’s right! The Open Graph Protocol requires that you must alwaysinclude the image property.
title
That’s right! The Open Graph Protocol requires that you must always include the title property.
Which of the elements below semantically divides your article content into parts that cover a specific topic?
<section>
That’s correct. The section element helps to divide the page into conceptual blocks.
When defining a social media card, how would you define the title?
<meta property=”og:title” content=”my title” />
That’s correct. The property attribute is rightly set to og:title.
True or false. More than one header element can exist in an HTML document?
True
That’s correct! There can be more than one header elements. For instance, when there are multiple articles in a page, each can have its own header.
When required to define a page refresh, which attribute value in <meta> must be set? Select all that apply.
http-equiv
That’s correct! The value should be set to ‘refresh’.
content
That’s correct! The numeric value of the refresh time interval is set by the content attribute.
Reading: Additional resources
Reading
The following resources will be helpful as additional references in dealing with different concepts related to the topics you have covered in this section.
Simple bare bones HTML webpage
HTML5/CSS bare-bones newsletter template
Add open graph social metadata- Twitter
Essential meta tags for social media
User Input and Forms
Video: Forms and validation
Why Form Validation Matters
- User Experience: Catching errors early prevents issues like undeliverable packages in an online ordering scenario.
- Data Integrity: Ensures the data you receive is usable and matches the format you need for your systems.
Types of Form Validation
- Client-side Validation
- Happens in the user’s browser (often using HTML5 and/or JavaScript).
- Provides instant feedback to the user.
- Example: Checking if an email field actually contains a valid email address.
- Server-side Validation
- Happens after the form is submitted, on your server.
- More secure, prevents malicious user tampering.
- Can do complex checks (database lookups, business logic).
Best Practice
Use BOTH client-side (for good user experience) and server-side (for security and data integrity).
HTML5 Input Types and the Required Attribute
- HTML5 offers input types like “email”, “tel”, “date” that have built-in browser validation.
- The “required” attribute makes a field mandatory, preventing submission until it’s filled.
As a developer, you can add client-side validation to a form by using specific input types.
Yes
Correct. Client-side validation checks for errors as soon as they are typed into the form. The web browser does this by validating the submitted data against the specified input type. The web browser will show an error message if the wrong type of input has been submitted.
You’ve most likely
encountered forms when registering an
account on a website, or when filling out your address for something you’ve
bought online. As a developer, you’ll use HTML forms to
capture user input. Capturing input is one thing, but the form also needs to
ensure the data is usable. How can you ensure the
user input is valid? For example, let’s say you are building an online
food delivery website. Say a user accidentally
makes an error when entering the delivery address
and the form accepts it, although the location
does not exist. It will cause a very
bad user experience when the food never arrives. This is where form
validation comes in. Form validation is a process that ensures that
the data entered by the user in a form is valid and conforms to rules
defined by the developer. There are two methods
of form validation, client-side validation and
server-side validation. Client-side
validation checks for errors as soon as they
are typed into the form. This is done by the web
browser or by JavaScript code, and provide the user
with immediate feedback. The client-side
validation process starts by checking if a form has
been filled out correctly. If there are no errors, the form will be submitted to
the server for processing. However, if there are errors, an error message will
alert the user of the invalid data and how to change it for
successful submission. For example, you decide to use the input element with its
type attributes set to email. If the user does not enter
a valid email address, the web browser will
display an error message informing them
that the data they entered is not a
valid email address. On the other hand, server-side
validation checks for errors after the data has been submitted to
the web server. Server-side validation is more secure because it
prevents malicious users from tampering with
your website’s code and submitting invalid
data to your server. When the form data is
received by the web server, the backend will validate the
data before processing it. This validation can run
more complex checks, such as checking the
data against a database, or validating the data against
business requirements. Most websites use
both client-side and server-side
validation to provide immediate feedback to users, but also to protect against malicious data submission and
to ensure data integrity. Let’s examine how HTML allows you to do simple
client-side validation. HTML has several input types that are validated
by the web browser. As demonstrated in the example, email is used for
email addresses. Others include “tel”
for telephone numbers, “url” for URLs such
as www.data.com, “date” for date values, “time” for time values, “number” for numeric values, “range” for numeric values which have a minimum and
maximum value, and “color” for color selection. Say for instance, a
user makes mistakes on a user account
form when entering a telephone number and URL, the browser will validate
the entered data against the requirements
of the input type and provide user feedback. Another example is the
required attribute, which indicates
that the user must supply a value to
an input field. The web browser will
alert a user if a required value is outstanding. That’s the basics of client and server-side validation of forms. You’ll learn more about HTML
validation capabilities in the next reading.
Reading: Input types
Reading
You already learned about the input HTML tag and how the type property determines the data your users can type in. This cheat sheet should be a reference to decide what type best suits your use case. Most of the inputs go hand in hand with the label tag for best accessibility practices.
Button
This displays a clickable button and it’s mostly used in HTML forms to activate a script when clicked. <input type=”button” value=”Click me” onclick=”msg()” />
Keep in mind you can also define buttons with the <button> tag, with the added benefit of being able to place content like text or images inside the tag.
<button onclick="alert('Are you sure you want to continue?')">
<img src="https://yourserver.com/button_img.jpg"
alt="Submit the form" height="64" width="64">
</button>
Checkbox
Defines a check box allowing single values to be selected or deselected. They are used to let a user select one or more options of a limited number of choices.
<input type="checkbox" id="dog" name="dog" value="Dog">
<label for="dog">I like dogs</label>
<input type="checkbox" id="cat" name="cat" value="Cat">
<label for="cat">I like cats</label>
Radio
Displays a radio button, allowing only a single value to be selected out of multiple choices. They are normally presented in radio groups, which is a collection of radio buttons describing a set of related options that share the same “name” attribute.
<input type="radio" id="light" name="theme" value="Light">
<label for="light">Light</label>
<input type="radio" id="dark" name="theme" value="Dark">
<label for="dark">Dark</label>
Submit
Displays a submit button for submitting all values from an HTML form to a form-handler, typically a server. The form-handler is specified in the form’s “action” attribute:
<form action="myserver.com" method="POST">
…
<input type="submit" value="Submit" />
</form>
Text
Defines a basic single-line text field that a user can enter text into.
<label for="fname">First name:</label>
<input type="text" id="fname" name="fname">
Password
Defines a single-line text field whose value is obscured, suited for sensitive information like passwords.
<label for="pwd">Password:</label>
<input type="password" id="pwd" name="pwd">
Date
Displays a control for entering a date with no time (year, month and day).
<label for="dob">Date of birth:</label>
<input type="date" id="dob" name="date of birth">
Datetime-local
Defines a control for entering a date and time, including the year, month and day, as well as the time in hours and minutes.
<label for="birthdaytime">Birthday (date and time):</label>
<input type="datetime-local" id="birthdaytime" name="birthdaytime">
Defines a field for an email address. It’s similar to a plain text input, with the addition that it validates automatically when submitted to the server.
<label for="email">Enter your email:</label>
<input type="email" id="email" name="email">
File
Displays a control that lets the user select and upload a file from their computer. To define the types of files permissible you can use the “accept” attribute. Also, to enable multiple files to be selected, add the “multiple” attribute.
<label for="myfile">Select a file:</label>
<input type="file" id="myfile" name="myfile">
Hidden
Defines a control that is not displayed but whose value is still submitted to the server.
<input type="hidden" id="custId" name="custId" value="3487">
Image
Defines an image as a graphical submit button. You should use the “src” attribute to point to the location of your image file.
<input type="image"src="submit_img.png" alt="Submit" width="48" height="48">
Number
Defines a control for entering a number. You can use attributes to specify restrictions, such as min and max values allowed, number intervals or a default value.
<input type="number" id="quantity" name="quantity" min="1" max="5">
Range
Displays a range widget for specifying a number between two values. The precise value, however, is not considered important. This is typically represented using a slider or dial control. To define the range of acceptable values, use the “min” and “max” properties.
<label for="volume">Volume:</label>
<input type="range" id="volume" name="volume" min="0" max="10">
Reset
Displays a button that resets the contents of the form to their default values.
<input type="reset">
Search
Defines a text field for entering a search query. These are functionally identical to text inputs, but may be styled differently depending on the browser.
<label for="gsearch">Search in Google:</label>
<input type="search" id="gsearch" name="gsearch">
Time
Displays a control for entering a time value in hours and minutes, with no time zone.
<label for="appt">Select a time:</label>
<input type="time" id="appt" name="appt">
Url
Displays a field for entering a text URL. It works similar to a text input, but performs automatic validation before being submitted to the server.
<label for="homepage">Add your homepage:</label>
<input type="url" id="homepage" name="homepage">
Week
Defines a control for entering a date consisting of a week-year number and a year, with no time zone. Keep in mind that this is a newer type that is not supported by all the browsers.
<label for="week">Select a week:</label>
<input type="week" id="week" name="week">
Month
Displays a control for entering a month and year, with no time zone. Keep in mind that this is a newer type that is not supported by all the browsers.
<label for="bdaymonth">Birthday (month and year):</label>
<input type="month" id="bdaymonth" name="bdaymonth" min="1930-01" value="2000-01">
Video: Creating a form
Purpose: The Little Lemon restaurant is creating a form for customers to sign up for accounts to enable online ordering.
Structure
<form method="post">
: This sets up the form, using the ‘post’ method for secure data submission.<div>
Elements: Each form field gets its own<div>
, likely for styling and layout.<input>
Elements:- Types include “text” (for name), “email” (built-in validation), and “password” (hides input)
- “name” attributes are vital for sending data to the server.
- “id” attributes are used to link labels.
Improving User Experience
<label for="...">
: Labels describe each field, used with the ‘for’ attribute that matches the input field’s “id”.- Submit Button: A
<button type="submit">
is needed to trigger form submission.
Key Takeaways
- This form will collect customer data (name, email, password) to create accounts.
- HTML5’s “email” input type provides basic validation.
- Labels are crucial for good user experience and accessibility.
- Back-end development is needed to actually process the form data.
You are asked to help create a signup form. What can you do to improve the user experience of the form? Select all that apply.
Ensure that the correct input types are used.
That’s right! Using specific input types makes it easier to complete a form correctly because users are warned if they enter an incorrect response.
Add labels for each input element.
That’s right! Labels will help users understand what they need to add in each field. It is important to set the ID attribute of each input field so that the corresponding label can be associated with it.
The Little Lemon restaurant wants to expand its service by taking online orders to deliver food to
customers at home. To do this, they
need their customers to set up an account
on their website. In this video, you will
learn how to create a simple signup form for user accounts on the
Little Lemon website. I’ve set up my basic
HTML document structure in a file named, signup.html. I start off by adding
the form element. The restaurant requires that the customer data
is sent securely. I will set the method
attribute to post so that is submitted using an
HTTP post request. You will learn more about different methods of
form submission later. For now, you just need
to know that if you send a form via an HTTP post request, it improves the data
security of the form. The restaurant wants to collect the customer’s first name, last name, and email address. Of course, the form also needs
a field for the password, and another to
confirm the password. I need to create a form
with five fields in total. I’ll start by adding
the input elements, also known as the form fields. First, I’ll set up
six div elements, one for each input element, and one for the sign up button. The div elements will
cause each field of the form to display
in its own CSS block. Now, I’ll start adding
the input elements. I add an input element for the first name to the
first div element. Since the user will input plain texts for this form field, I set the type
attribute to text. I also set the name and id
attributes to user_first_name. Remember that the
name attribute sets the key for the value
submitted to the web server. Later in this video, I’ll explain why I
set the ID attribute. Next, I add an input
element for the last name. Like the first name element, I set the type
attribute to text, and the name and ID
attributes to user_last_name. I then add an input element
for the email address. To make sure users enter a valid email address
in this field, I set the type
attribute to email. Earlier you learned
that doing so establishes HTML’s
client-side validation. I also set the name and ID
attributes to user_email. Next, I add the input
element for the password. I want the password to be hidden on screen as the user types it, so I set the type
attribute to password. When an input field
is set to password, each character
that a user enters will display as a
placeholder character, such as the bullet point. The content in the field
will contain the password that the user enters,
but it will be hidden. I then set the name and ID
attributes to user_password. Finally, I add the input element for confirming the password. Again, I set the
type to password to hide the content of the
input field on screen. I then set the name and ID attributes to
user_confirm_password. Now that our input
fields are set up, I save the file and open the Live Preview to
check the webpage. Everything displays correctly. However, I’d like to
improve the user experience by informing the user what
each field represents. To do this, I’ll
add a label element before each input element. Now I want to explain why I set the ID attribute for each input field
earlier in the video. The reason for this, is that it allows me to associate a label with
each input element. Labels improve the
user experience and assist accessibility software
and understanding the form. I now add a label element
above the first input element. Inside the label element, I add the descriptive
text for the input field. In this case, the text
description will be first name. Then, to associate the
label with the input field, I add the four attribute
and set its value to match the value of the ID attribute
of the input element. Finally, I’ll add a
line break tag after the label element so that the input field displays
below the label. I then repeat the same process
for each input element. I save the file again and
open the Live Preview. Oh, yes, that’s much better. The form labels now display
above the input fields. To finalize the form, I need to add one more
thing, the submit button. Inside the last div element, I add a button element. I set the button type
attribute to submit. Then inside the button element, I add the text, sign up. I save the file again and
open the Live Preview. The form is now ready to use. Once the backend is set up by a backend developer to accept the data
submitted via the form, users will be able to
create their accounts. In this video, you
learned how to create a basic form with several
different input fields, each in its own CSS block, you covered how
to set the method attribute to submit the
form in a secure way, and you also now know
how to associate a label with an input field to
improve the user experience. Good luck with creating
your own signup forms.
Video: Making the most of client-side validation
Improving Forms with HTML Validation and CSS Styling
- Why Client-Side Validation Matters: Prevents unnecessary server requests and improves user experience by catching errors before the form is submitted.
- Key HTML Attributes
- required: Ensures a field isn’t left empty.
- minlength: Sets the minimum acceptable character length for input.
- maxlength: Sets the maximum acceptable character length for input.
- CSS for Error Styling
- input:invalid pseudo-class: Targets input fields with invalid data. Lets you customize styling (e.g., red border).
- input:focus pseudo-class: Used to only show the error style when the user is actively typing in that field, preventing “false positives” on page load.
Key Takeaways
- These techniques provide a smoother form experience for users.
- More advanced validation options become available as you learn JavaScript.
What additional attributes can you add to an element on an HTML form to improve client-side validation? Check all that apply.
minlength
That’s right. You can specify the minimum number of characters required for a form field by adding for example:
minlength=”3″ inside the input type element.
maxlength
That’s right. You can specify the maximum number of characters allowed for a form field by adding for example:
maxlength=”12″ inside the input type element.
required
That’s right. If it is essential that a user submit a response to a specific field on your form, you should add:
Required inside the input type element.
Have you ever completed
a form online and then after you’ve clicked
on the submit button, one of the fields turned red. There are many reasons for error messages when you
complete online forms, the format could be wrong, but sometimes an error
results when a field is empty or if a value is
too long or too short. As a developer, you can
use HTML and CSS to guide users to enter the correct data on
forms and in this way, save web server resources. In this video, you
will learn more about the capabilities of
client-side validation in HTML and how to use CSS to effectively alert users
when data is incorrect. By now you’ve learned about the different HTML input types and how they validate
the format of data, but there are additional
attributes that you can apply to elements for
further validation. First, let’s explore
how you can ensure that the user provides a
value to a form field. This example of a log-in
form contains two fields, one for the username and
one for the password. It also contains a submit
button to submit the form. If a user hasn’t
added a username or password and clicks
the “Submit” button, the browser will allow the form to submit
to the web server. But this is a waste of server
resources because although the server-side
validation will pick up the missing information and prevent the processing
of the request, a HTTP request was
still submitted. Let’s improve this form by using client-side validation to ensure the user enters values
to both fields. Now with the required
attribute in the code, if one of the
fields is empty and the user clicks
the submit button, the request will not be
submitted to the web server. The web browser will focus on the first empty
input element and inform the user that
a field is empty. Now the form creates a much
better user experience and prevents unnecessary usage
of web server resources, but user input that is
too short or too long would also result in unnecessary submissions
to the web server. So another way to
validate user input is to specify the required
length for data. Let’s say you want the
usernames to be at least three characters long and a
maximum of 12 characters, or maybe you want to ensure
more secure passwords by requiring a minimum
password length of five characters. Fortunately, there are two
more attributes you can use to ensure the
correct length of data. You can add the min
length and max length attributes to the fields to
specify the required length. In this case, since the minimum value for the
username is set to three, a two-character entry
would be invalid. If you click the
submit button now, the web browser will inform you of the length requirements. A built-in function
of the browser will generate the message
displayed on screen. Again, a much better
user experience and management of web
server resources. Now let’s focus on
the way the browser communicates errors
to the users, like a form field that turns red when the data is invalid. This can be readily
implemented using CSS. To highlight a field in red
when the data is invalid, you use the input
element selector. You then apply the pseudo-class
selector called invalid. You will learn more about
pseudo-class selectors later in this course. For now, the key thing
to know is that they are used to select elements
based on their state, such as whether the input
data is valid or invalid. Then you add a CSS property to set the border of
the element to read. But since all the
form fields are empty when the form
loads initially, their state is still
practically invalid. This will cause all form
fields to display read from the start like demonstrated in this Real-world example
of a login screen. Ideally, you only
want fields to appear red as the user
enters invalid data. To do this, you need to apply another pseudo-class
called focus, which checks if the
user is currently entering data into this field. Now the form will
appear normal when the page first loads, and when the user
starts inputting data, the field will turn red
if the data is invalid. This video gave you a brief introduction
to how you can use client-side validation and CSS pseudo-class
selectors to improve the user experience of forms. As you learn more about
JavaScript in other courses, you will be able to use even
more advanced techniques to improve form validation.
Lab: Create and test a form
Reading
Instructions
In this exercise, you’ll create a basic login form for the Little Lemon website. The form will contain two fields: one for the username and another for the password. Both fields are required fields and must have a minimum text length of 2. The form will also contain a button to submit the form.
Instructions
Step 1: First add a form element to the body of the HTML document.
Step 2: Next, add two div elements; one for the username field and one for the password.
Step 3: In the first div element, add a label element for the username.
Step 4: After the label, add an input element for the username.
Step 5: Add the required and minlength attributes. Set the minlength attribute value to 2 so that the field requires a minimum text length of 2.
Step 6: Add an id attribute to the input element. Ensure that the for attribute of the label is set to match the id.
Step 7: In the second div element, add a label element for the password.
Step 8: After the label, add an input element for the password. Ensure the correct input type is used so that the inputted data is not visible on screen.
Step 9: Add an id attribute to the input element. Ensure that the for attribute of the label is set to match the id.
Step 10: Add the required and minlength attributes to the input element. Set the minlength attribute value to 2 so that the field requires a minimum text length of 2.
Step 11: Add a name attribute to all input elements.
Step 12: After the second div element, add a button element containing the text “Log In”.
Step 13: Set the type attribute of the button element to submit.
Step 14: Save the HTML document and open it in Live Preview.
Step 15: Click the Log In button and note if the form submits successfully. The form submits successfully when no errors are displayed and the content of the form resets.
Step 16: Add one character of text to both input fields. Again, click the Log In button and note if the form submits successfully.
Step 17: Type the text “admin” in the username field. Then type the text “password” in the password field. Click the Log In button and note if the form submits successfully.
When you complete the exercise, the web page should be similar to the following image.
Code
<!DOCTYPE html>
<html lang="en">
<head>
<title>Little Lemon</title>
<meta property="og:title" content="Our Menu">
<meta property="og:type" content="website">
<meta property="og:image" content="logo.png">
<meta property="og:url" content="https://littlelemon/">
<meta property="og:description" content="Little Lemon is a family-owned Mediterranean restaurant, focused on traditional recipes served with a modern twist.">
<meta property="og:locale" content="en_US">
<meta property="og:site_name" content="Little Lemon">
<link rel="stylesheet" href="styles.css">
</head>
<body>
<header>
<img src="logo.png">
</header>
<main>
<div>
<label for="username">Username</label>
<input type="text" id="username" required minlength="2">
</div>
<div>
<label for="password">Password</label>
<input type="password" id="password" required minlength="2">
</div>
<button type="submit">Log In</button>
</main>
</body>
</html>
Reading: Create and test a form (solution)
Reading
The following code is an example solution for the previous exercise.
This code is placed inside the <main> element of index.html.
<form>
<div>
<label for="username">Username</label>
<input type="text" id="username" required minlength="2">
</div>
<div>
<label for="password">Password</label>
<input type="password" id="password" required minlength="2">
</div>
<button type="submit">Log In</button>
</form>
While reviewing the code, note the following items:
- The label for attribute value matches the value of the id attribute on the corresponding input element
- The type attribute is set to text for the username input
- The type attribute is set to password for the password input
- Each field has a required attribute to enable client-side validation which checks that the form is filled out by the user
- Each field has a minlength attribute with its value set to 2. This enables client-side validation which will prompt the user if the content of the field is less than 2 characters.
Practice Quiz: Self review: Create and test a form
When the input fields contained no text and you clicked the Log In button, what was the result?
The web browser notified that the required field must be completed
Correct. The fields were marked as required so they must be filled out before submitting.
When the input fields contained a single text character and you clicked the Log In button, what was the result? Select all that apply.
- The password field changed to a red color
- The username field changed to a red color.
- The web browser notified that the minimum length is 2
When the username field contained the text “admin” and the password field contained the text “password”, what was the result when you clicked the Log In button?
The form submitted successfully
Correct. The fields were valid so it submitted correctly.
Video: Radio buttons
Scenario: Little Lemon restaurant is adding an online table booking system to their website.
Why Radio Buttons?
- They’re ideal for limited choices where the user can only select one option within a group (table size or indoor/outdoor seating).
HTML Structure
- <fieldset>: Defines a group of radio buttons. Use multiple fieldsets for separate groups (e.g., size and location).
- <input type=”radio”>: Creates each radio button.
- value: The value submitted when the option is selected.
- name: Groups buttons together; must match the fieldset’s id.
- checked: Makes an option the default selection.
- <label>: Wraps text with its corresponding button, so clicking the text selects the option (improves usability).
Example:
HTML
<fieldset id="size">
<input type="radio" value="two" name="size"> <label>Two-person table</label>
<input type="radio" value="four" name="size" checked> <label>Four-person table</label>
</fieldset>
Key Points:
- Each group of radio buttons needs a unique
name
attribute. - Only one radio button within a group can be selected at a time.
You’ve surely booked
something online before. Perhaps it was tickets to a show or accommodation
for a holiday. The ability to book things
online is super convenient. That’s one of the reasons why the Little Lemon
restaurant is adding a table booking system
to their website. By now, you should know that a HTML form will be an
ideal solution for that. Like most restaurants,
Little Lemon has different table sizes and different sections
in the restaurant where customers can be seated. Therefore, the HTML
form must allow customers to decide between
the available table sizes, as well as if they want to
sit indoors or outdoors. Since both choices have
limited options available, it will be best to use radio
buttons for the input. Radio buttons are ideal for this forum because they
allow me to set up groups of options of which only one option and the
group can be selected. Now, let’s explore how to set up a HTML form with radio buttons. I’ve opened Visual
Studio Code and added a new file called booking.html. I’ve set up the
basic HTML structure and added a form element. First, I’ll add to
fieldset elements, one for the table size
and one for location. The fieldset element defines a group for the radio buttons. Without the fieldset elements, all radio buttons will
belong to the same group, but for this form,
we need two groups. On the first fieldset element, I set the id attribute to size. On the second fieldset element, I set the id attribute
to location. Below the fieldset elements, I add a button element. On the button element, I set the type attribute to submit. Inside the element, I
add the text book table. There are three different tables sizes available at Little Lemon; two-person, four-person,
and six person tables. Inside the first
fieldset element, I add three input elements representing the three
different tables sizes. On the first input element, I set the type attribute to radio and the value
attribute to two. I then set the name
attribute to size. It is important to set the
name attribute value to match the value of the id
attribute in the fieldset. This tells the browser, which fieldset the
input belongs to. After the element, I add
the text two-person table. On the second input element, I set the type attribute to radio and the value
attribute to four. I then set the name
attribute to size. After the element, I the
text, four-person table. Since the four-person table
is the most common booking, I want to have this option
selected by default. To do this, I add the checked attribute
to this input element. On the third input element, I set the type
attribute to radio and the value attribute to six. I then set the name
attribute to size. After the element, I add
the text, six-person table. In the second fieldset element, I add two input elements representing the table
location at the restaurant. On the first input element, I set the type
attribute to radio and the value
attribute to indoors. I then set the name
attribute to location, matching the id of the
second fieldset element. Since the indoor booking
is the most common, I’ll add the checked
attribute to this input element so that
it is selected by default. On the second input element, I set the type
attribute to radio and the value
attribute to outdoors. Again, I set the name
attribute to location. I save the file and open
it in Live Preview. Success. The form is
set up correctly. Let’s test it. If I choose an option for the table size and then
choose a different option, my previous choice
is deselected. The table location
field behaves the same. I can only choose
indoors or outdoors. However, I’m testing this form on a laptop with a large screen. On a mobile device with
a way smaller screen, it may be difficult
for the user to accurately select the
small button elements. Luckily, there is a
way to improve this by setting the text and
button as the input area. I open booking.html again, for each input
element and texts, I wrap them in a label element, which will group the texts
with the input element. I save the file again and
return to Live Preview. If I click on the text now, the corresponding input
element is selected. Selecting the desired
choice will be much easier on a
mobile device now. A user will be able to select
the button specifically. This form has a much better
user experience now. In this video, you’ve
covered how to use radio buttons to create a
simple online booking form. Hopefully, Little Lemon will get a lot more table bookings now.
Reading: Cheat sheet: Interactive form elements
Reading
When filling in HTML forms, we expect users to abide by certain rules, like using numbers when asked to, or properly formatting a URL or an email when needed. However, humans are prone to errors and in some cases, they may overlook some of the data they input. That’s why it’s important to ensure the shape of the data we expect in each field is correct. HTML form validation is a set of attributes we can add to form inputs to perform automatic validation on the user’s behalf. The most important attributes you’ll find yourself using for validation are the following.
Required
Denotes a mandatory input that the user can’t leave empty. It can be used with any input type, like password, radio, text and so on.
<input type="text" id="firstName" name="firstName" required>
Maxlength
Specifies the maximum length of a text input, in other words, the maximum number of characters that can be entered for a specific field. If provided, it will prevent the user from entering more characters than the limit.
<input type="text" id="description" name="description" maxlength="50">
Minlength
Specifies the minimum length of a text input. If set, the input will not accept fewer characters than those specified.
<input type="password" id="password" name="password" minlength="8">
Min and max attributes
Determine the minimum and maximum values allowed for an input field. They are usually applied to numerical text inputs, range inputs or dates.
<input type="number" id="quantity" name="quantity" min="1" max="10"> <input type="range" id="volume" name="volume" min="1" max="100">
Multiple
Indicates that the user can enter more than one value in a single input field. This attribute can only be used for email and file input types.
<input type="file" id="gallery" name="gallery" multiple>
Pattern
Defines a particular pattern that an input field value has to fulfill to be considered valid. This attribute expects a regular expression to specify the pattern. It works with text, date, search, URL, tel, email and password input types. For example, you can restrict phone numbers to be only from the UK.
<input type="tel" id="phone" name="phone" pattern=”^(?:0|\+?44)(?:\d\s?){9,10}$” >
Video: Using interactive form elements
Key Changes
- Table Size → Number of People: More flexible for accommodating groups.
- Removed Location: Replaced with a dropdown to handle multiple restaurants.
- Added Booking Date: Important for reservations.
Advanced HTML Input Types
- Date Input
- <input type=”date”>
- Displays an interactive calendar for easy date selection.
- Example:
<label for="booking_date">Booking Date:</label>
<input type="date" id="booking_date" name="booking_date">
Range Input
- <input type=”range”>
- Creates a slider for selecting a value within a range.
- Use
min
andmax
attributes to set the range limits. - Example:
<label for="booking_people">Number of People:</label>
<input type="range" id="booking_people" name="booking_people" min="1" max="10">
Datalist Input
- <input type=”text” list=”datalist_id”>
- <datalist id=”datalist_id”> <option> … </option> </datalist>
- Creates a dropdown list with suggested options.
- User can select from the list or type to filter suggestions.
- Good for handling multiple locations, as the list can easily be updated.
- Example
<label for="booking_location">Location:</label>
<input type="text" id="booking_location" name="booking_location" list="locations">
<datalist id="locations">
<option value="Downtown">
<option value="Uptown">
</datalist>
Important Note: Always use <label>
tags with input fields to enhance accessibility and user experience!
If you must add a question on a form where users need to pick an option from a very long list, you can add a datalist input type which will allow the user to begin typing to narrow down the available options based on their input.
Yes
That’s right. The Datalist input type is also useful when the list of options might become longer in future.
Little Lemon
restaurant is becoming very popular in
their local area, so much so that they’ve opened a second Little Lemon
in another area nearby. Because of this,
they want to update the form of their
table booking system. In this video, you
will learn how to add advanced HTML
features to a form. They’ve also added some new
tables to the restaurant. They’ve also asked to replace
the table size field with a field for the number of people and to remove the
table location field. Finally, they want
customers to be able to choose which restaurant
they want to book at. The owners have told me
that they’re hoping for continued success and
growth of the business, and so I should plan for more restaurant
locations to be added. I opened booking.html
in Visual Studio Code. I’ll start by
deleting the previous table and location fields. I then add three div
elements for the new fields. Next, I’ll add the field
for the booking date. Luckily, HTML provides a
built-in field type called date that’ll present a calendar to the customer when
the field is clicked. To add this, I add
an input element to the first div element and set
its type attribute to date. I also set the ID and name
attributes to booking_date. To provide a good
user experience, I’ll add a label element
before the input element. Inside the label element, I add the text
description, booking date. I also add the for attribute and set its value
to booking_table so that accessibility
software can describe the purpose of the input
field to its users. Next, I’ll add the field
for the number of people. The restaurant has told me that the maximum booking
is 10 people, so I’ll use the
range input type. The range type
allows me to specify the minimum and maximum
values of the field. I add an input element to
the second div element. I set its type
attribute to range. I also set its ID and name
attributes to booking_people. To set the minimum value, I add the attribute min, which is short for minimum, and set its value to one. Then to set the maximum value, I add the attribute max, which is short for maximum, and set its value to 10. Again, to provide a
good user experience, I add a label before the element and set its content
to number of people. I then set the for attribute
to booking_people. Now, I’ll add the
new location field. The restaurant currently
has two locations, but they said they
might add more later. To allow for expansion later, I’ll use a data
list, input type. The data list input type
allows me to specify a list of available options that will
appear in a drop-down list. There can be tens and
hundreds of options, so the field allows the
user to begin typing, and it will narrow down the available options
based on their input. Since there are only
two locations so far, the customer will
be able to select their location from
the drop-down list. When more locations
are added later, the customer will be able to
begin typing their location and quickly select
their location from a reduced set of options. Setting up the data
list input type requires a few more steps
than the other input types. First, I add an input element. Then I set the name and ID attributes to booking_location. Then I add an attribute called list and set its
value to locations. This value is important
for the next step. I then add a data
list element and set the ID attribute
to match the value of the list attribute
on the input element. In this case, I set the ID
attribute to locations. Inside the data list element, I then add two option elements. On the first option element, I add the value attribute
and set it to Downtown. On the second option element, I add the value attribute
and set it to Uptown. Again, to provide a
good user experience, I add a label before the input element and set
its content to location. I then set the for attribute
to booking_location. I save the file, and
open it in live preview. When I click on the date field, the browser opens a calendar and allows me to select a date. The range input type is
presented as a slider that I can slide left and
right to the value I want. Finally, the data list input allows me to select
an option for the location or begin typing to narrow down
the available options. In this video, you
learned how to use advanced features of HTML forms. You should now be able
to add a calendar, create a slider with values, and add a datalist that
allows users to either select an option from the
drop-down list or by typing their option. With the continued
success of Little Lemon, I’m sure I’ll be updating this form again in
the near future.
Practice Quiz: Knowledge check: Declaring form elements
You are building a calendar web application; which of the following input types can be used? Select all that apply.
- <input type=”date”>
- <input type=”week”>
- <input type=”month”>
You want to define a dropdown of selectable options. However, you also want users to be able to input their responses as well. Which of the following is the most suitable form element to wrap available options?
datalist
That’s correct! Using datalist, you provide suggestions that users may or may not select. With the input filed, they are free to add their response.
For the following code block, what is the most suitable input type that will ensure that only a single option is selected?
<form>
<input type="----" id="alpha" name="letters" value="Alpha">
<label for="html">Alpha</label><br>
<input type="----" id="beta" name="letters" value="Beta">
<label for="css">Beta</label><br>
<input type="----" id="gamma" name="letters" value="Gamma">
<label for="javascript">Gamma</label>
</form>
radio
That’s correct! Radio is used to select a single option.
When defining a form, which element is almost always defined?
<input>
Correct! In almost any form, some element is required to get user input.
True or false. The following form element will clear the form validation errors.
<input type="reset">
False
That’s correct! The reset value will reset the form contents to default values.
A developer has added the following input element to a HTML form. What client-side validation is applied? Select all that apply.
<input type="email" required minlength="4">
The user input must be in an email address format
That’s correct. The type attribute is set to email which will validate that the input is a valid email address format.
The user must provide a value to the input field
That’s correct. The required attribute will ensure that the user provides a value to the input field.
The minimum length of the user input must be 4 chararacters.
That’s correct! The minlength attribute is applied to the element and its value is set to 4.
Video: Form submission
Submitting Form Data
- HTTP Request/Response: Browsers communicate with web servers using HTTP requests (from browser) and responses (from server).
- Data Submission: Forms can send data to the server within these requests, crucial for online orders and account logins.
Methods for Sending Data
- HTTP GET
- Data is appended to the URL (visible in the address bar).
- Problems:
- Limited URL length (may lose data in large forms).
- Security risks (data is exposed in browser history & server logs).
- HTTP POST
- Data is inserted into the body of the HTTP request.
- Advantages:
- Handles larger amounts of data
- More secure than GET
- Can be further secured with HTTPS encryption
Choosing the Right Method
- GET: Use for simple searches or non-sensitive data where visibility in the URL is okay.
- POST: The preferred choice for login forms, orders, or anything containing personal information.
When ordering products online, you fill out your address
and your credit card number, then you click on
an Order button that confirms your order. Because you are learning more about front-end
development, you might be wondering
what exactly happens when you click
on that order button. In this video, you will
learn what happens when forms are submitted
in the web browser. By now, you know that the web
browser communicates with a web server using a HTTP
request response cycle. This means that the web browser sends requests to
the web server, and the web server
sends back a response. Up to now, the main type of requests you’ve
been introduced to were for resources
such as HTML documents, images, CSS files,
and JavaScript files. But it is also possible to send data as part of a request. This is how form send
data to the web server. In fact, there are
two ways a form can send data to the
web server using the HTTP GET method or
the HTTP POST method. You can specify which
method the form should use with the method attribute
of the form element. Let’s examine an example
form and see how the data can be sent using
the two different methods. This login form, excepts
a username and password. It also has a login button that submits the form
to the web server. How would it work if the method
attribute is set to GET? When the Login
button is clicked, the form data is sent as
part of the request URL. This means that the user
data is appended to the end of the URL in the
web browser navigation bar. The web server receives
the HTTP GET request, and extracts the form
data from the URL. While this is an easy
way to submit data, it has three key problems. First, the length of a
URL is limited to around 2,000 characters depending on the web browser you’re using. Some web browsers allow more, but there are inconsistencies
between browsers. So if you have a large form, some data may be lost when it sent via the GET Method
to the web server. Second, the length
of a requested URL is also limited on
some web servers. Popular web server software such as Apache web
server or Engine X, have a default limit of
around 4,096 characters. Again, if you have a large form, some data may be lost. The final problem is security. Since the data is included
as part of the URL, it means that your
data is stored in your web browser history and possibly in the request
logs on the web server. If you’re transmitting
personal information such as addresses or
credit card numbers, this is a major privacy
and security risk. Now, let’s focus on
how the form would work if we set the method
attribute to post. When the form is submitted
using the post method, the form data is inserted into the content of the HTTP request. When the submit
button is pressed, it will send an
HTTP post request with the data contained in
the body of the request. The HTTP post method is more secure than the HTTP GET method. However, the data
could still be read by a third party listening
to the HTTP request. To secure this completely, HTTPS is used to
encrypt the data so that only the sender and receiver can
understand the data. Once the web server
receives the request, it processes it and sends
back an HTTP response. If the request was successful, the response will direct the web browser
to a new webpage. If errors occurred, there
are many ways this can be handled by the webpage as
explained in a previous video. You should now be
familiar with how forms are sent to web servers, and the difference
between GET and POST.
Reading: Submit
Reading
You have recently learned about how forms are sent to web servers and the difference between Get and Post. In this reading, you will build on this knowledge by learning about Submit.
Action and method
Form submissions are an essential part of the world wide web. Nearly every website uses forms, from buying items online to ordering food for delivery. When you click the login button on a website, it sends your username and password to a web server to log you into your account. As you know by now, you add a form to your web page using the form tag.
<form>
</form>
But how the form is submitted is determined by two essential attributes: action and method. The action attribute specifies to which web address the form must be sent. This is address is location of server-side code that will process the request.
<form action="/login">
</form>
It is important to note that action can be a full URL address such as https://meta.com, an absolute path such as /login, or a relative path such as login. The absolute path, which starts with a forward slash, will use the base address of the current website, such as https://meta.com and combine it with the absolute path. For example, if /login is the absolute path, the form will be submitted to https://meta.com/login. If the address is https://meta.com/company-info/ and /login is the absolute path, the submission address will still be https://meta.com/login. Similarly, a relative path will combine the current web address with a relative path. For example, if the web browser is currently on the web page https://meta.com/company-info/, and the relative path is set to login, the form will be submitted to https://meta.com/company-info/login. The method attribute specifies which HTTP method is used to submit the form; GET or POST.
<form method="get">
</form>
<form method="post">
</form>
The form will default to the HTTP GET method when the method attribute is not provided. As you may already know, when the form is submitted using the HTTP GET method, the data in the form’s fields are encoded in the URL. And when the form is submitted using the HTTP POST method, the data is sent as part of the HTTP request body. When the web server receives the request, it processes the data and sends back an HTTP response. The response indicates the result of the submission, which can be successful or fail due to invalid or incorrect data. However, as a front-end developer, it is essential to know that forms are not the only way to submit data to the web server. As you learn more about JavaScript and front-end libraries, you’ll discover that developers often submit HTTP requests directly via code and send data as part of the HTTP request body in a text format called JavaScript Object Notation, or JSON. But that is a topic for another course. For now, practice building HTML forms and submitting data to the web server using the different attributes available.
Practice Quiz: Knowledge check: Form submission
Which form attribute is used to specify the address to which the form data will be submitted to?
action
That’s correct. The action attribute specifies the URL to submit the data to.
Which HTTP method will be used to send data for the following form?
<form>
<button type="submit">Submit</button>
</form>
GET
That’s correct. When the method attribute is not specified, GET is the default HTTP method used.
When using the HTTP POST method to submit form data, how is the data transmitted to the server?
Via the body of the HTTP request
That’s correct. The form data is encoded as part of the request body.
Your web browser is currently at the address https://meta.com/profile. When the following form is submitted, what address will it submit to?
<form>
<button type="submit">Submit</button>
</form>
https://meta.com/profile
That’s correct. When the action attribute is not specified, the form will default to the same URL, in this case, https://meta.com/profile.
Your web browser is currently at the address https://meta.com/profile. When the following form is submitted, what address will it submit to?
<form action="/login">
<button type="submit">Submit</button>
</form>
https://meta.com/login
That’s correct. The action attribute starts with a forward slash so it is an absolute path. Therefore, /login is appended to https://meta.com.
Your web browser is currently at the address https://meta.com/profile. When the following form is submitted, what address will it submit to?
<form action="login">
<button type="submit">Submit</button>
</form>
https://meta.com/profile/login
That’s correct. The action attribute does not start with a forward slash, so it is a relative path. Therefore, login is appended to the current url.
The HTTP DELETE method can be used for form submission.
False
That’s correct. Only HTTP GET and POST methods can be used for form submission.
There are several ways to secure transmitting form data to the web server. Which of the following will help secure the data? Select all that apply.
Send the data using HTTPS
That’s correct. HTTPS will encrypt the data before sending.
Send the data using the HTTP POST method
That’s correct. The form data will be sent as part of the request body which means it will be more secure than HTTP GET but still obtainable by a malicious third party.
Video: Browser differences
Problem: Form Element Inconsistencies
- HTML forms can render differently across different browsers (Firefox, Edge, Chrome, Safari, etc.) and even on different operating systems.
- This includes variations in input box size, borders, checkbox appearance, and colors.
- This creates a potential for a disjointed user experience.
Solution: CSS for Consistent Styling
- CSS (Cascading Style Sheets) lets you precisely control the visual appearance of HTML elements.
- You can use CSS rules to target specific form elements (e.g., input fields, checkboxes) and define consistent styles:
- Element selectors: Target elements directly (
input
,checkbox
) - Input type selectors: Style based on input type (
input[type="text"]
) - Properties: Control font, width, height, border, etc.
- Element selectors: Target elements directly (
Simplifying the Process
- Popular CSS frameworks like Bootstrap, Tailwind CSS, and Foundation provide pre-made form styles.
- These ensure a polished and consistent look across different browsers and devices with less manual CSS work.
Key Takeaway: It’s important to be aware of form rendering differences and use CSS to create a unified and professional user experience across all browsers and platforms.
What are the advantages of styling HTML forms with CSS? Check all that apply.
You can specify styling for element types using element selectors
That’s right. Alternatively, you can specify the styling of individual elements. When you style HTML forms with CSS it will display the same across browsers creating a consistent user experience.
You can specify the styling of individual elements.
That’s right. Alternatively, you can style element types using element selectors. When you style HTML forms with CSS it will display the same across browsers creating a consistent user experience.
It creates a consistent user experience across browsers.
That’s right. By default, browsers handle forms differently but if you style a form with CSS all browsers will display the form in the same way.
An important part of being a front-end developer
is to provide a good user experience on the websites and web
applications that you develop. That includes ensuring
that users can complete HTML forms
without issues. There are many web browsers available today for browsing
the World Wide Web. However, each one
is developed by a different company using
different technologies. As a result, you will find
that your HTML forms will appear differently when you view them on different web browsers. But a form may even
appear differently on the same browser when you view the form on a
Windows PC or a Mac. This makes the creation of a consistent user
experience challenging. In this video, you will explore how form elements displayed differently on
various web browsers and how to solve this problem. First, let’s focus on the most common form
element, the input elements. The same input type HTML code displays differently in web
browsers such as Firefox, Microsoft Edge,
Chrome, and Safari. For example, there are
subtle differences in the height and corners
of the input box. There is also a difference in the default input box widths of Firefox and Safari compared to other browsers like
Microsoft Edge and Chrome. Safari on Mac OS
differs a lot from the other browsers using a thinner border on
regular corners. Next, let’s explore the
checkbox input type. Again, the exact same
input type HTML code, will let the checkbox
displayed differently in a checked and unchecked
state in different browsers. Notice that Microsoft Edge uses a gray color
in the check state, while the other web
browsers use blue, even still, each browser is using a different
shade of blue. Also notice how the border of the checkbox varies
between each web browser. Safari’s checkbox is also
smaller than the other. Now that you’ve explored
how HTML form elements can appear inconsistently
across different web browsers, let’s focus on how
to solve this. As you know, CSS
allows you to define the visual styling
of HTML elements. Defining CSS rules for the
different HTML form elements will ensure that your
element is styled consistently across
web browsers. For example, you can use
elements selectors to select a different element types and apply CSS properties to them. It’s also possible to study the individual input
types using CSS rules. You can add a CSS rule
using the element selector. To select the input
HTML element, use the input element selector, and then specify the
individual styling by adding a pair of
square brackets, and then type equals in
this case text or email. Then apply CSS properties
to set the font, width, height, and border. If you specify styling
with CSS in this way, the individual elements
of your forms will display consistently
across browsers. Luckily, there are
a lot of resources that simplify the
styling of forms. Popular libraries and frameworks such as Bootstrap, Tailwind CSS, and Foundation provides
CSS rules for forms, uninsured visual
consistency across different devices and browsers. You should now know why it is
important to pay attention to the appearance of
different HTML elements across web browsers, and how you can ensure
consistency with CSS rules.
Reading: Glossary: HTML form elements
Reading
The <form> element in HTML is an important and useful element. The following sheet provides an overview of the <form> constituent elements and their common attributes with simple examples for quick reference.
<input>
It is used to create interactive controls, for example, buttons and various types of text fields and so on, to accept input or data from the user. The key attribute of this element is type. Some common values for the type include: button, checkbox, date, email, number, password, submit, text, and url. These values dictate the appearance of the element. For example, this code:
<form action="my_action_page">
<label for="uname">Username:</label>
<br>
<input type="text" id="uname" name="username">
<br>
<label for="pwd">Password:</label>
<br>
<input type="password" id="pwd" name="pwd">
<br><br>
<input type="submit" value="Login">
</form>
Results in the following output:
Note how the type password hides the user input.
<label>
Defines a label for an element. It has an attribute “for”, the value of which should be equal to the id attribute of the element it is associated with. Note how in the example above, the <label> is associated with the <input> using its id value.
<select>
Defines a drop-down list of options presented to the user. It has a couple of attributes:
- Form, the id of the form in which the drop-down appears
- Name specifies the name of the control
- Multiple Boolean attribute, when specified, indicates if a user can select multiple options out of the list
- Required indicates if the user is required to select an option before submitting a form
- Size mentions the number of visible options in a drop-down list
The options in a drop-down list are defined using the <option> element inside <select>. Note the example in the <option> description below.
<textarea>
Defines a multi-line input field, typically to allow the user to input longer textual data. The common attributes for this element include:
- cols defines the width of the text area, the default value is 20
- form the form element the text area is associated with
- maxlength when specified, limits the maximum number of characters that can be entered in the text area
- minlength the minimum number of characters that the user should enter
- readonly once set, the user cannot modify the contents
- rows defines the number of visible text lines for the text area
The following line of code defines a text area of 10 visible lines and nearly 30 characters wide where the user can input a maximum of 200 characters:
<textarea name="response" rows="10" cols="30" maxlength=”200”>
</textarea>
<button>
Defines a clickable button. The onclick attribute defines the behavior when the button is clicked by the user. For example, in the code below, an alert message is shown to the user.
<button type="button" onclick="alert('You just clicked!')">Click Me!
</button>
<fieldset>
Used to group related input elements in a form. For instance, elements related to the user’s personal information and educational qualification can be grouped separately in two field sets.
<legend>
Defines a caption for the <fieldset> element. For example:
<fieldset>
<legend>Personal Info</legend>
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="John"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="Doe"><br>
</fieldset>
<fieldset>
<legend>Qualificaiton</legend>
<label for="pdegree">Primary degree:</label><br>
<input type="text" id="pdegree" name="degree" value="Masters"><br>
<label for="fos">Last name:</label><br>
<input type="text" id="fos" name="field" value="Psychology"><br>
</fieldset>
<datalist>
Specifies a list of pre-defined options for an input element. It differs from <select> since the user can still provide textual or numeric input other than the listed options.
<form action="/my_action_page">
<label for="flowers">Favourite flower:</label><br>
<input list="flowers" name="flowers">
<datalist id="flowers">
<option value="Rose">
<option value="Lily">
<option value="Tulip">
<option value="Daffodil">
<option value="Orchid">
</datalist>
...
</form>
<output>
Represents the result of a calculation (typically the output of a script) or the outcome of the user action.
<option>
Defines an option for the drop-down list. The following code example demonstrates how a simple list can be defined, with the rendered view below the code block.
By default, the first item in the drop-down list is selected. To define a pre-selected option, add the selected attribute to the option.
<optgroup>
Defines a group of related options in a drop-down list. Its attribute label names the group.
Lab: Create a complex form
Reading
Instructions
Step 1: First add a form element to the body of the HTML document.
Step 2:Next, add four div elements; one for each input field.
Step 3: In the first div element, add a label element and an input element for the email address. Ensure that you use the correct type attribute to the input element to apply client-side validation.
Step 4: In the second div element, add a label element and an input element for the date of booking. Set the type attribute to date to allow for a date picker to appear when the user interacts with the form. Note that if using Live Preview, the date picker will not appear. However, if you launch the web page in a new web browser tab, it will appear.
Step 5: In the third div element, add a label element and an input element for the number of people. Set the type attribute to number and apply the appropriate attributes so that the minimum value is 1 and the maximum value is 8.
Step 6: In the fourth div element, add a label element. Set the text of the label element to “I agree to the cancellation policy”.
Step 7:Add an input element to the label and set its type attribute to checkbox. Apply the required attribute to the element.
Step 8: After the fourth div element, add a button element and set its text to “Book Now”. Set its type attribute to submit.
Step 9: For each input element, add a name attribute.
Step 10: Save the HTML document and open it in Live Preview.
Step 11: Click the date of booking field. Note the result.
Step 12: Type the word “hello” into the email address field. Set the date field to today and the number of people to 1.
Note The date picker element is not supported in the Live Preview.
Step 13: Click the checkbox and then click the Book Now button. Note the result.
Code
<!DOCTYPE html>
<html lang="en">
<head>
<title>Little Lemon</title>
<meta property="og:title" content="Our Menu">
<meta property="og:type" content="website">
<meta property="og:image" content="logo.png">
<meta property="og:url" content="https://littlelemon/">
<meta property="og:description" content="Little Lemon is a family-owned Mediterranean restaurant, focused on traditional recipes served with a modern twist.">
<meta property="og:locale" content="en_US">
<meta property="og:site_name" content="Little Lemon">
<link rel="stylesheet" href="styles.css">
</head>
<body>
<header>
<img src="logo.png">
</header>
<main>
</main>
</body>
</html>
Reading: Create a complex form (solution)
Reading
The following code is an example solution for the previous exercise.
This code is placed inside the <main> element of index.html.
<form>
<div>
<label for="email_address">Email Address</label>
<input type="email" id="email_address" name="email_address">
</div>
<div>
<label for="booking_date">Date of Booking</label>
<input type="date" id="booking_date" name="booking_date">
</div>
<div>
<label for="people">Number of people</label>
<input type="number" id="people" min="1" max="8" name="people">
</div>
<div>
<label>
<input type="checkbox" id="agree" name="agree" required>
I agree to the cancellation policy
</label>
</div>
<button type="submit">Book Now</button>
</form>
While reviewing the code, note the following:
- The type attribute is set to email for the email address field. This will enable client-side validation to ensure that the user enters a correctly formatted email address.
- The type attribute is set to date for the booking date field. This will enable the browser’s built-in date picker for the field.
- The type attribute is set to number for the number of people field. This will use the browser’s built-in number picker for the field.
- The min attribute is added to the people input element to set the minimum value to 1.
- The max attribute is added to the people input element to set the maximum value to 8.
- The checkbox input element is contained inside the label element. For mobile devices, this will improve the user experience so that the user can touch either the checkbox or the text “I agree to the cancellation policy” to toggle the checkbox.
- The checkbox input element has a required attribute. This will require that the user agrees to the cancellation policy before being able to book a table.
Practice Quiz: Self-review: Create a complex form
What attribute did you apply to the number of people field to set the minimum value?
min
Correct. The min attribute is used to set the minimum value of range inputs.
When you clicked the date of booking field, what was the result?
A date picker was displayed
Correct. The date input type will provide a date picker to the user.
When you typed the word hello into the email address field and submitted the form, what was the result?
The web browser prompted to fix the email address format
That’s correct! The email input type ensures correct email address formatting.
Practice Quiz: Knowledge check: User input and forms
When the user clicks the submit button of the following form, what will happen? Select all that apply.
<form method="POST">
<input type="text" name="username">
<input type="password" name="password">
<button type="submit">Log In</button>
</form>
It will use the resources of the server unnecessarily.
That’s right! The browser proceeds with the submission.
The browser will still allow form submission.
That’s right! The browser proceeds with the submission.
The server-side will prevent the processing of the request if server-side validation is implemented.
That’s right! The server-side will still pick up the information missing but prevent the processing of the request.
What attribute should be added to the <input> element to ensure the user provides a response?
required
That’s correct! When the required attribute has been added it specifies that the input field can’t be empty.
What is the risk of using the HTTP GET method for form submission? Check all that apply.
The web address may exceed the maximum length accepted by the web server.
That’s right! The maximum address length for requests varies between servers which may lead to data loss.
The form data will be stored in the browser history.
That’s right! Since the data is sent as part of the web address, it will be stored in the web browser’s history.
The form data will be sent insecurely.
That’s right! Since the data is sent as part of the web address it is easily exposed during transmission.
Which of the following is a framework that provides CSS rules for forms and visual consistency? Check all that apply.
Foundation, Bootstrap, Tailwind CSS
The web browser sends a ____ to the web server, and the web server sends back a ____. This is done by means of the HTTP ____ method which accepts values as part of the URL or the HTTP ____ method which submits the values in our form as part of the request.
Fill in the blank with the correct order from the options below:
A. GET
B. POST
C. Request
D. Response
CDAB
That’s right! The web browser sends a request to the web server, and the web server sends back a response. This is done by means of the GET method, which accepts values and the POST method, which submits the values in our form.
Which of the following values can fill the blank?
The form action attribute consists of _____ as values. Select all that apply.
Relative URL, An absolute URL
That’s right. form action can consist of relative URLs.
Reading: Additional resources
Reading
The following resources will be helpful as additional references in dealing with different concepts related to the topics you have covered in this section.
Client-side validation of forms with HTML5