Java Reference
In-Depth Information
Figure 8.8. Validation error alert dialog
We can improve the usability of the form further by giving instant feedback instead of wait-
ing for the form to be submitted. This can be achieved by adding the event listener directly
to the input field that will fire when the user leaves the field (using the blur event). The
feedback can then be inserted into the label for the input field (along with a class of error
for styling purposes) for more direct feedback. Add the following code to scripts.js:"blur",validateInline,false);
function validateInline(event) {
// get the fist letter of the name input field
var firstLetter =[0];
// get a reference to the label for the name input field
var label = document.querySelector("label[for='name']");
if (firstLetter.toUpperCase() === "X") {
label.textContent = "Your name is not allowed to start
with X!";
} else { // the error hasn't happened or has been fixed
label.textContent = "Name:";
The else block ensures that if the error has been fixed, the error class is removed and
the label text is returned to normal.
We also should add some styling to the error message so that it stands out. Add the follow-
ing to styles.css:
background: #f99;
border: #900 1px solid;
Now if you refresh the page and try to enter a name beginning with “X,” you should see an
error message above the input field as soon as you try to move to another field. This can be
seen in the screenshot in Figure 8.9 .
Search WWH ::

Custom Search