.onfocus .onblur

Theses events can used to provide helping text within a form's field elements that is activated when the user clicks or tabs to a specific form field element .onfocus,  or moves out of the form field element .onblur

 

Form example showing .onfocus and .onblur

<html>
	<head>
		<title>JavaScript</title>
	</head>
	<body>
		<form id="myForm" name="myForm" method="post" action="index.php">

			<label for="aName">Name:</label>
			<input type="text" value="Please enter your name." name="aName" id="aName" tabindex="1" />
			<br>
			<label for="email">Email:</label>
			<input type="text" name="email" id="email" tabindex="2" />
			<br>
			<label for="bikeType">Motorbike: </label>
			<input type="text" name="bikeType" id="bikeType" tabindex="3" />
			<br>
			<input type="submit" name="submit" id="submit" value="Submit" tabindex="4" />

		</form>

		<script>
			var yourName = document.getElementById("aName");

			yourName.onfocus = function() {
				if ( yourName.value == "Please enter your name.") {
					yourName.value = "";
				}
			};

			yourName.onblur = function() {
				if ( yourName.value == "") {
					yourName.value = "Please enter your name.";
				}
			};
		</script>
	</body>
</html>

Leave a Reply