これを行う 1 つの方法は、html を使用することです。
<form action="" method="post">
<fieldset>
<label for="emailAddress">Sign up for the newsletter</label>
<input type="text" id="emailAddress" name="email" />
<button id="submitButton" type="submit">Submit</button>
</fieldset>
</form>
そして JavaScript:
var emailEntry = document.getElementById('emailAddress');
var button = document.getElementById('submitButton');
var defaultButtonText = button.innerHTML;
emailEntry.onblur = function(){
var val = this.value;
// the following IS NOT a valid test of email address validity
// it's for demo purposes ONLY
if (val.length < 5 && val.indexOf('@') == -1){
button.innerHTML = 'retry';
button.style.color = 'red';
}
else {
button.innerHTML = defaultButtonText;
button.style.color = 'black';
}
};
button.onclick = function(){
// prevent submission of the form if the email was found invalid
// and the innerHTML was therefore set to 'retry'
if (this.innerHTML == 'retry'){
return false;
}
};
JS フィドルのデモ。