BogoToBogo
  • Home
  • About
  • Big Data
  • Machine Learning
  • AngularJS
  • Python
  • C++
  • go
  • DevOps
  • Kubernetes
  • Algorithms
  • More...
    • Qt 5
    • Linux
    • FFmpeg
    • Matlab
    • Django 1.8
    • Ruby On Rails
    • HTML5 & CSS

HTML5 Tutorial: Forms - 2020

HTML5-Number5.png




Bookmark and Share





bogotobogo.com site search:




4. Forms

Web application developers find themselves continually in need of some more sophisticated form controls, such as spinners, sliders, date/time pickers, color pickers, and so on.


In order to tap into these types of controls, developers needed to use an external JavaScript library that provided UI components, or else use an alternative development framework such as Adobe Flex, Microsoft Silverlight, or JavaFX.

HTML5 aims to fill some of the gaps left by its predecessor in this space by providing a whole range of new form input types. Search boxes, text inputs, and other fields get better controls for focusing, validating data, interacting with other page elements, sending through email, and more.

In addition to these new input types, HTML5 also supports two major new features for form fields. The first of these is the placeholder attribute, which allows the developer to define the text that will appear in a textbox-based control when its contents are empty. An example of this would be a search box where the developer would prefer not to use a label outside the box itself. The placeholder attribute allows the developer to specify text that will show when the value of the control is empty and the control does not have focus. The second enhancement is autofocus, which tells a browser to automatically give focus to a particular form field when the page has rendered, without requiring JavaScript code to do so.



4.1 Placeholder Text

The first improvement HTML5 brings to web forms is the ability to set placeholder text in an input field. Placeholder text is displayed inside the input field as long as the field is empty and not focused. As soon as we click on or tab to the input field, the placeholder text disappears.



Here's how we can include placeholder text in our own web forms:

<form>
  <input name="myInput" placeholder="Search Bookmarks and History">
  <input type="submit" value="Search">
</form>

Browsers that don't support the placeholder attribute will simply ignore it.

4.2 Autofocus Field

Many web sites use JavaScript to focus the first input field of a web form automatically. While this is convenient for most people, it can be annoying for power users or people with special needs. If we press the space bar expecting to scroll the page, the page will not scroll because the focus is already in a form input field. (It types a space in the field instead of scrolling.) If we focus a different input field while the page is still loading, the site's autofocus script may move the focus back to the original input field, disrupting our flow and causing us to type in the wrong place.

Because the autofocusing is done with JavaScript, it can be tricky to handle all of these edge cases, and there is little recourse for people who don't want a web page to steal the focus.

To solve this problem, HTML5 introduces an autofocus attribute on all web form controls. The autofocus attribute does exactly what it says on the tin: as soon as the page loads, it moves the input focus to a particular input field. But because it's just markup instead of script, the behavior will be consistent across all web sites.

Example of setting a form field to autofocus:

<form>
  <input name="myName" autofocus>
  <input type="submit" value="Search">
</form>

As it happens to the placeholder, browsers that don't support the autofocus attribute will simply ignore it. If we want our autofocus fields to work in all browsers, not just these HTML5 browsers, we can keep our current autofocus script with just two small changes:

  1. Add the autofocus attribute to our HTML markup
  2. Detect if the browser supports the autofocus attribute, and only run our own autofocus script if the browser doesn't support autofocus natively.
<form name="myForm"> 
<input id="myInput" autofocus> 
<script> 
if (!("autofocus" in document.createElement("input"))) {
	document.getElementById("myInput").focus(); 
} 
</script> 
<input type="submit" value="Go"> </form>

4.3 Email Address

The most common web forms that we've been using are:

Field Type HTML Note
checkbox <input type="checkbox"> can be toggled on or off
radio button <input type="radio"> can be grouped with other inputs
password field <input type="password"> echoes dots instead of characters as we type
drop-down lists <select> <option>...  
file picker <input type="file> pops up an open file dialog
submit button <input type="submit">  
plain text <input type="text"> the type attribute can be omitted

All of these input types still work in HTML5. If we upgrade to HTML5, we don't need to make a single change to our web forms. However, HTML5 defines several new field types, and for reasons that will become clear in a moment, there is no reason not to start using them. The first of these new input types is for email addresses. It looks like this:

<form>
  <input type="email">
  <input type="submit" value="Go">
</form>

All browsers support type="email". They may not do anything special with it, but browsers that don't recognize type="email" will treat it as type="text" and render it as a plain text field.

The web has millions of forms that ask us to enter an email address, and all of them use <input type="text">. We see a text box, we type our email address in the text box. Along comes HTML5, which defines type="email". Do browsers freak out? No. Every single browser on Earth treats an unknown type attribute as type="text" - even IE 6. So we can upgrade our web forms to use type="email" right now.

The HTML5 specification doesn't mandate any particular user interface for the new input types. Opera styles the form field with a small email icon. Other HTML5 browsers like Safari and Chrome simply render it as a text box - exactly like type="text" - so our users will never know the difference (unless they view-source).


4.4 URLs

URLs are another type of specialized text. The syntax of a web address is constrained by the relevant Internet standards. If someone asks us to enter a web address into a form, they're expecting something like "//www.google.com/", not "125 Farwood Road." Forward slashes are common - even Google's home page has three of them. Periods are also common, but spaces are forbidden. And every web address has a domain suffix like .com or .org.

<input type="url">

Browsers that don't support HTML5 will treat type="url" exactly like type="text", so there's no downside to using it for all our web-address-inputting needs.


4.5 Spinbox

Pick a number. A number in a particular range. We may only want certain kinds of numbers within that range - maybe whole numbers but not fractions or decimals, or something more esoteric like numbers divisible by 10. HTML5 has we covered.

<input type="number"
       min="0"
       max="10"
       step="2"
       value="6">

Here is how it looks like:

Opera respects the HTML 5 spinbox, and it looks like this:

Let's take that one attribute at a time.

  1. type="number" means that this is a number field.
  2. min="0" specifies the minimum acceptable value for this field.
  3. max="10" is the maximum acceptable value.
  4. step="2", combined with the min value, defines the acceptable numbers in the range: 0, 2, 4, and so on, up to the max value.
  5. value="6" is the default value. This should look familiar. It's the same attribute name we've always used to specify values for form fields.

That's the markup side of a number field. Keep in mind that all of those attributes are optional. If we have a minimum but no maximum, we can specify a min attribute but no max attribute. The default step value is 1, and we can omit the step attribute unless we need a different step value. If there's no default value, then the value attribute can be blank or even omitted altogether.

But HTML5 doesn't stop there. For the same low, low price of free, we get these handy JavaScript methods as well:

  1. input.stepUp(n) increases the field's value by n.
  2. input.stepDown(n) decreases the field's value by n.
  3. input.valueAsNumber returns the current value as a floating point number. (The input.value property is always a string.)

As with all the other input types, browsers that don't support type="number" will treat it as type="text". The default value will show up in the field (since it's stored in the value attribute), but the other attributes like min and max will be ignored. We're free to implement them ourselves, or we could reuse one of the many JavaScript frameworks that have already implemented spinbox controls. Just check for the native HTML5 support first, like this:

if (!Modernizr.inputtypes.number) {
  // no native support for type=number fields
  // maybe try Dojo or some other JavaScript framework
}

Modernizr is an open source, MIT-licensed JavaScript library that detects support for many HTML5 & CSS3 features. We should always use the latest version. To use it, include the following <script>element at the top of our page.

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>HTML 5</title>
  <script src="modernizr-1.6.min.js"></script>
</head>
<body>
  ...
</body>
</html>

Modernizr runs automatically. There is no modernizr_init() function to call. When it runs, it creates a global object called Modernizr, which contains a set of Boolean properties for each feature it can detect. For example, if our browser supports the canvas API, the Modernizr.canvas property will be true. If our browser does not support the canvas API, the Modernizr.canvas property will be false.

if (Modernizr.canvas) {
  // let's draw some shapes!
} else {
  // no native canvas support available :(
}


4.6 Slider

Check how does slider controls look like in our browser:


The look may be different depending on the browsers.

IE, FireFox Opera Chrome

We can now have slider controls in our web forms, too. The markup looks similar to spinbox.

<input type="range"
       min="0"
       max="10"
       step="2"
       value="6">

All the available attributes are the same as type="number", min, max, step, value, and they mean the same thing. The only difference is the user interface. Instead of a field for typing, browsers are expected to render type="range" as a slider control. At time of writing, the latest versions of Safari, Chrome, and Opera all do this. All other browsers simply treat the field as type="text", so there's no reason we can't start using it immediately.







Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization

YouTubeMy YouTube channel

Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong







HTML5 & Javascript



Why HTML5?

HTML 5 Tutorial

Introduction

New Semantic Elements

Canvas

Forms

Offline Storage

Geolocation

Video and Audio

Video and Audio - Before HTML5

CSS

Updating a span when input text changes using DOM API, jQuery, and Backbone

Javascript : text input and event listener




Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong









Data Visualization



Data Visualization Tools

Basics of HTML DOM and D3

Basic D3 Drawings

Data Visualization D3.js

Inscribe triangle with animation

Data Visualization - List of D3.js samples







AngularJS



Introduction

Directives I - ng-app, ng-model, and ng-bind

Directives II - ng-show, ng-hide, and ng-disabled

Directives III - ng-click with toggle()

Expressions - numbers, strings, and arrays

Binding - ng-app, ng-model, and ng-bind

Controllers - global controllers, controller method, and external controllers

Data Binding and Controllers (Todo App)

Todo App with Node

$scope - A glue between javascript (controllers) and HTML (the view)

Tables and css

Dependency Injection - http:fetch json & minification

Filters - lower/uppercase, currenty, orderBy, and filter:query with http.get()

$http - XMLHttpRequest and json file

Module - module file and controller file

Forms

Routes I - introduction

Routes II - separate url template files

Routes III - extracting and using parameters from routes

Routes IV - navigation between views using links

Routes V - details page

AngularJS template using ng-view directive : multiple views

Nested and multi-views using UI-router, ngRoute vs UI-router

Creating a new service using factory

Querying into a service using find()

angular-seed - the seed for AngularJS apps

Token (JSON Web Token - JWT) based auth backend with NodeJS

Token (JSON Web Token - JWT) based auth frontend with AngularJS

Twitter Bootstrap

Online resources - List of samples using AngularJS (Already launched sites and projects)

Meteor Angular App with MongoDB (Part I)

Meteor Angular App with MongoDB (Part II - Angular talks with MongoDB)

Meteor Angular App with MongoDB (Part III - Facebook / Twitter / Google logins)

Scala/Java Play app with Angular

Laravel 5 / Angular Auth using JSON Web Token (JWT) - Prod

Scala/Java Play app with Angular





Node.JS



Node.js

MEAN Stack : MongoDB, Express.js, AngularJS, Node.js

MEAN Stack Tutorial : Express.js with Jade template

Building REST API with Node and MongoDB

Nginx reverse proxy to a node application server managed by PM2

Jade Bootstrap sample page with Mixins

Real-time polls application I - Express, Jade template, and AngularJS modules/directives

Real-time polls application II - AngularJS partial HTML templates & style.css

Node ToDo List App with Mongodb

Node ToDo List App with Mongodb - II (more Angular)

Authentication with Passport

Authentication with Passport 2

Authentication with Passport 3 (Facebook / Twitter Login)

React Starter Kit

Meteor app with React

MEAN Stack app on Docker containers : micro services

MEAN Stack app on Docker containers : micro services via docker-compose





Ruby on Rails



Ruby On Rails Home

Ruby - Input/Output, Objects, Load

Ruby - Condition (if), Operators (comparison/logical) & case statement

Ruby - loop, while, until, for, each, (..)

Ruby - Functions

Ruby - Exceptions (raise/rescue)

Ruby - Strings (single quote vs double quote, multiline string - EOM, concatenation, substring, include, index, strip, justification, chop, chomp, split)

Ruby - Class and Instance Variables

Ruby - Class and Instance Variables II

Ruby - Modules

Ruby - Iterator : each

Ruby - Symbols (:)

Ruby - Hashes (aka associative arrays, maps, or dictionaries)

Ruby - Arrays

Ruby - Enumerables

Ruby - Filess

Ruby - code blocks and yield

Rails - Embedded Ruby (ERb) and Rails html

Rails - Partial template

Rails - HTML Helpers (link_to, imag_tag, and form_for)

Layouts and Rendering I - yield, content_for, content_for?

Layouts and Rendering II - asset tag helpers, stylesheet_link_tag, javascript_include_tag

Rails Project

Rails - Hello World

Rails - MVC and ActionController

Rails - Parameters (hash, array, JSON, routing, and strong parameter)

Filters and controller actions - before_action, skip_before_action

The simplest app - Rails default page on a Shared Host

Redmine Install on a Shared Host

Git and BitBucket

Deploying Rails 4 to Heroku

Scaffold: A quickest way of building a blog with posts and comments

Databases and migration

Active Record

Microblog 1

Microblog 2

Microblog 3 (Users resource)

Microblog 4 (Microposts resource I)

Microblog 5 (Microposts resource II)

Simple_app I - rails html pages

Simple_app II - TDD (Home/Help page)

Simple_app III - TDD (About page)

Simple_app IV - TDD (Dynamic Pages)

Simple_app V - TDD (Dynamic Pages - Embedded Ruby)

Simple_app VI - TDD (Dynamic Pages - Embedded Ruby, Layouts)

App : Facebook and Twitter Authentication using Omniauth oauth2

Authentication and sending confirmation email using Devise

Adding custom fields to Devise User model and Customization

Devise Customization 2. views/users

Rails Heroku Deploy - Authentication and sending confirmation email using Devise

Deploying a Rails 4 app on CentOS 7 production server with Apache and Passenger I

Deploying a Rails 4 app on CentOS 7 production server with Apache and Passenger II

OOPS! Deploying a Rails 4 app on CentOS 7 production server with Apache and Passenger (Trouble shooting)











Contact

BogoToBogo
contactus@bogotobogo.com

Follow Bogotobogo

About Us

contactus@bogotobogo.com

YouTubeMy YouTube channel
Pacific Ave, San Francisco, CA 94115

Pacific Ave, San Francisco, CA 94115

Copyright © 2024, bogotobogo
Design: Web Master