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>
</form>

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>
</form>

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...
addClass();
// 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)
addClass();
};
} 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) {
e.target.setCustomValidity("");
if (!e.target.validity.valid) {
e.target.setCustomValidity("Please enter a comment.");
}
});
commentArea.addEventListener('input', function (e) {
e.target.setCustomValidity("");
});

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.

Ajaxify

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 .

With

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

主题: JavaJavaScriptHTMLXMLAjaxCSSFila
分页:12
转载请注明
本文标题:Enhancing a comment form: From basic to custom error message to BackgroundSync
本站链接:http://www.codesec.net/view/480847.html
分享请点击:


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 前端(javascript) | 评论(0) | 阅读(38)