When building a web site, sooner or later, you will probably have to implement a form, be it a login form or a comment form. I have done it many times before, and the last time I had to create a comment form, I thought about how far I can enhance it. After adding one enhancement, another enhancement crossed my mind and after implementing that yet another one.

That’s why I would like to show you how you can enhance a form (in this case consisting of an <input> for the name, a <textarea> for the message and a submit <button> ) from the most basic version to an EnhancedEnhanced Version with BackgroundSync.

Basic Version

We start with the basic version, a HTML form:

<form action="./" method="post">
<label for="name">Name</label>
<input type="text" name="name" id="name">
<label for="comment">Comment</label>
<textarea name="comment" id="comment"></textarea>
<button type="submit">Publish</button>

This will work in *every* browser. From here we start adding enhancements without breaking the basic version.

Here is a demo of the basic version.

Enhanced HTML version
Enhancing a comment form: From basic to custom error message to BackgroundSync

The first thing we do is adding an required attribute to our Textarea and as it should never be empty. If the browser supports HTML form validation we get validation out of the box without using javascript. We shouldn’t, however, rely on it (not supported browsers, browser bugs , …) so it is always a good idea to validate form values on the server side.

<form action="./" method="post">
<label for="name">Name</label>
<input type="text" name="name" id="name">
<label for="comment">Comment</label>
<textarea required placeholder="What's on your mind?" name="comment" id="comment"></textarea>
<button type="submit">Publish</button>

Next, we add an placeholder attribute as a nice extra touch. Always keep in mind that you should never replace a label with a placeholder, it’s a great enhancement, but not a replacement.

Here is a demo of the enhanced HTML version.

Cut the mustard

For further enhancements we will use JavaScript. First, we add acut the mustard test to the <head> of our page. We are using a technique I first encountered in the article Enhancing optimistically by the Filament Group.

if( 'visibilityState' in document ) {
// include loadJS here...
function loadJS( src ){ ... }
// This is a capable browser, let's improve the UI further!
var docElem = window.document.documentElement;
// the class we'll use to enhance the UI
var enhancedClass = "enhanced";
var enhancedScriptPath = "enhanced.js";
// add enhanced class
function addClass(){
docElem.className += " " + enhancedClass;
// remove enhanced class
function removeClass(){
docElem.className = docElem.className.replace( enhancedClass, " " );
// Let's enhance optimistically...
// load enhanced JS file
var script = loadJS( enhancedScriptPath );
// if script hasn't loaded after 8 seconds, remove the enhanced class
var fallback = setTimeout( removeClass, 8000 );
// when the script loads, clear the timer out and add the class again just in case
script.onload = function(){
// clear the fallback timer
clearTimeout( fallback );
// add this class, just in case it was removed already (we can't cancel this request so it might arrive any time)
} Custom error messages
Enhancing a comment form: From basic to custom error message to BackgroundSync

With our feature test in place we will add custom error messages, as “Please fill out this field.” isn’t a really nice message. In our enhanced.js script (which will only be loaded in capable browsers) we add the following to define a custom message:

// set a custom text for the error message
var commentArea = document.querySelector("#comment");
commentArea.addEventListener('invalid', function (e) {
if (!e.target.validity.valid) {
e.target.setCustomValidity("Please enter a comment.");
commentArea.addEventListener('input', function (e) {

In this case we show the message “Please enter a comment” when a user submits the form without a comment. You may have noticed that I haven’t talked about styling the error messages so far. That’s because currently there is now way to style them with CSS. There used to be ::-webkit-validation-bubble for webkit-based browsers, but it has been removed. If you really want to style them you need to build your own validation bubble but be aware that there are many things which may go wrong so I would advise using the default bubbles as they give you all for free.

Here is a demo of the custom error message version.


All modern browsers now get a custom error message when the user tries to submit an empty comment, but if they enter a comment the form is still submitted server-side and therefore a page reload is necessary. Let’s enhance it by posting the comment via JavaScript.

// send form data with JavaScript
// send form data with JavaScript
if( window.FormData) {
var appendComment = function (nameValue, commentValue) {
var comment = document.createElement('li');
var commentWrapper = document.querySelector('.comments');
nameValue = nameValue ? ' ' + nameValue + '

' : ''; comment.innerHTML = nameValue + '

' + commentValue + '

'; commentWrapper.appendChild(comment); }; form.addEventListener('submit', function (ev) { var formData = new FormData(form); commentValue = commentArea.value; nameValue = nameInput.value; var xhr = new XMLHttpRequest(); // save the comment in the database xhr.open('POST', './save', true); xhr.onload = function () { appendComment(nameValue, commentValue); }; xhr.send(formData); // always call preventDefault at the end, see: http://molily.de/javascript-failure/ ev.preventDefault(); }); }

First we check if the browser supports FormData , an advanced XMLHttpRequest feature. If it does, we define a function appendComment() to append the new comment to the other comments. Next, we add and eventListener to our form to make an XMLHttpRequest on submit. If the request was successfull we append the comment. At the very end we call preventDefault to prevent the default behaviour of the form. It is important to call preventDefault at the end as we cannot be sure if the JavaScript might fail .


本文前端(javascript)相关术语:javascript是什么意思 javascript下载 javascript权威指南 javascript基础教程 javascript 正则表达式 javascript设计模式 javascript高级程序设计 精通javascript javascript教程

主题: JavaJavaScriptHTMLXMLAjaxCSSFila
本文标题:Enhancing a comment form: From basic to custom error message to BackgroundSync

技术大类 技术大类 | 前端(javascript) | 评论(0) | 阅读(19)