[jsメモ]focusとblurイベントのフォーム検証
4874 ワード
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>Insert title heretitle>
head>
<body>
<form method="post" action="#">
<label for="username">Create a userName:label> <input type="text"
id="username" />
<div id="feedback">div>
<label for="password">Create a password:label> <input
type="password" /> <br> <input type="submit" value="Sign up!" />
form>
<script type="text/javascript">
function checkUsername() {
var username = el.value;
if (username.length < 5) {
elMsg.className = 'Warning';
elMsg.textContent = 'Not long enough, yet...';
} else {
elMsg.textContent = '';
}
}
function tipUsername() {
elMsg.className = 'tip';
elMsg.innerHTML = 'Username must be at least 5 characters';
}
var el = document.getElementById('username');
var elMsg = document.getElementById('feedback');
// focus ,
el.addEventListener('focus', tipUsername, false);
// blur ,
el.addEventListener('blur', checkUsername, false);
script>
body>
html>