onblur textbox
using javascript onblur events on an html textbox
Using an onblur event in a textbox couldn't be simpler:
The blur event, that's handled by an onblur function is triggered by an element when it's losing focus - typically caused by a user clicking 'out' of the element or 'tabbing' to the next element, perhaps in a form.
There are two sorts of textboxes that you have to think about - a basic input element with one line and the larger multiline textarea.
In the case of an input element that may look like :
<input name="firstname" size="20" />
all you'd need to do is something like:
(in all of these examples I've used the xhtml style '/>' on the end of the tags - if you're using more traditional html then a simple '>' may be enough.
<input name="firstname" size="20" onblur="doSomething();" />
of course, you'd need to define doSomething() somewhere else.
For testing, to understand when the onblur event is triggered you could use:
<input name="firstname" size="20" onblur="alert(this.value);" />
or, to check if a field is valid (very very simplistically)
<input name="email" onblur="if(this.value.indexOf('@')==-1) alert('That's not an email address!');" />
The case of a text area is similar, although a textarea generally always has a closing tag, so you'd need something like:
<textarea name="comments" onblur="alert('comment: ' + this.value);"></ textarea>
(only without the extra space I had to pop in between the '/' and 'textarea' - sorry)
If you use MS Internet Explorer then you'll probably find that you can attach an onblur handler to most elements, but this may not be supported on other browsers which will limit the use of this in some cases (although textboxes of any sort should be fine).
Finally, consider the use of the change event and the onchange handler - this will trigger at the time time as onblur (more or less) but will only trigger when a field has changed its value - so if someone is clicking around a form before filling it in, it won't cause your stuff to fire unnecessarily.
Comments
Comments for this page are now closed.