The validator is telling you that the doctype you’ve chosen does not allow things like
onclick
onfocus
onblur
etc
in the HTML (similarly, you’re probably not allowed to have things like align=“center” either).
The solution to it is to have your Javascript find those inputs itself, and then assign onfocus and onblur event handlers to them.
If multiple events need to be set to these inputs, you’ll want event listeners to make a list of event handlers (since otherwise if you just plug a bunch of handlers on an element, only the last one gets run).
Javascript can either grab the inputs by name or by id.
Did you place the script at the end of the body, so that it’s capable of attaching those events as the page loads?
If it still doesn’t work for you, then please show us what you’re doing. A test page up on the internet is the best way of showing us.
For reference, here’s a simple test page. Please note, the only reason for the inline script is so that the full code can be posted in one code block. You should ensure that your scripts are in a separate file from your HTML code when using this for real.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
</head>
<body>
<form id="login">
<input type="text" name="username" value="enter username...">
</form>
<script type="text/javascript">
function clearText() {
var field = this;
if (field.defaultValue == field.value) {
field.value = '';
} else if (field.value == '') {
field.value = field.defaultValue;
}
}
var form = document.getElementById('login');
form.elements.username.onfocus = clearText;
form.elements.username.onblur = clearText;
</script>
</body>
</html>
How many browsers did you test that in? If event attachment was indeed this simple I doubt jQuery or prototype.js would have need of event handling sub systems.
Also this attachment approach doesn’t allow for multiple events of the same type on the object which might come up eventually.
There are always more complicated ways of doing things, such as using addEventListener after DOMContentReady.
The code sample that was provided is the simplest that does the job, allows for an easy understanding of the mechanics involved, and provides a useful path by which more complex requirements can later on be met on an as needed basis.
It’s hard to tell someone who’s at the level of the code originally posted what to do next, because a whole boatload of other things come into play:
-this not working in IE
-the script not running if you stick it in the head without some kind of loader script elsewhere
Usually why when I try to learn how to do something the answer is always “don’t bother learning javascript, just use a library, it does all that stuff for you” : (
and then all the pitfalls said library gets around cross-browser, take me forever to figure out.
The OP is probably going to run into the need for event listeners once more than one function needs to run onevent.