HTML and CSS Reference
In-Depth Information
event handler function cancels the default event processing (with
event.preventDefault() ) in order to prevent the message from the
browser from also appearing.
Triggering validation with JavaScript
A browser will only trigger form validation when the form is submit-
ted. This is sensible: having error messages pop up repeatedly while the
user's trying to fill in the form would be distracting.
There may be occasions when you want to trigger validation without
submitting the form—possibly the allowed values for a later field
on the form depend on the user already having entered a valid email
address, or maybe the input isn't part of a form at all.
Suppose you have an email input in your HTML , like this:
<input id="email" type="email">
You can trigger validation by calling the checkValidity() method:
document.getElementById('email').checkValidity();
In Opera, the field will be validated as it would be when the form is
submitted. Thus if the email address is invalid, the normal message
will pop up, although this isn't required by the spec. The method also
works in Firefox 4 and recent Chrome and Safari releases, returning
false if the email address is invalid. You can use the return value to
implement your own notifications.
Responding to any changes in value
Before HTML5 , when you had to write your own form-validation code,
it was a common technique to attach the JavaScript validation to the
onchange event handler. But in HTML4 , onchange was only a valid attri-
bute on <input> , <select> , and <textarea> , and it was fired only when the
form control that changed lost focus.
An event handler is a hook HTML provides to JavaScript to let you run
code when particular things happen. You might want to know when the
page finishes loading ( onload ), or when the user clicks something
( onclick ), or, as in this case, when the user leaves an input field in
which the value has changed ( onchange ). When the event happens, it is said
to fire . Check appendix D for more on event handlers.
Search WWH ::




Custom Search