While these spans
are empty and hence don??™t contribute to page layout, it??™s a little inelegant, and they clutter
the resultant HTML. It would be tidier if the JavaScript added and removed the spans itself.
Remember that you can??™t just assume that JavaScript detecting an error means that you
should add a span??”if the server code detects an error it will correctly write out that error
message. So, on detecting an error, the script needs to check whether there??™s an error span
already present. If there is, alter its content; if there isn??™t, create one.
Listing 7-3 is a relatively simple addition to the existing Listing 7-2; nothing needs to
change other than the JavaScript checkField() function.
Listing 7-3. checkField() from simple-form-tidier-js-create-spans.php
checkField: function(e) {
fld = window.event ? window.event.srcElement : e.target;
fieldname = fld.id;
if (validator.VALIDATIONS[fieldname]) {
re = validator.VALIDATIONS[fieldname]["regexp"];
if (fld.value.search(re) == -1) {
// the regular expression didn't match
// find the span.error element for this field
// and put the error message in it
spans = fld.parentNode.getElementsByTagName('span');
CHAPTER 7 n FORM VALIDATION AND JAVASCRIPT 156
if (spans.length == 0) {
// there is no error span, so, create one
span = document.createElement('span');
span.className = 'error';
fld.parentNode.appendChild(span);
} else {
span = fld.
Pages:
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230