フォーム送信時に空欄を確認・空欄の色を変更(elements, borderColor, background)
<html>
<head>
<title>フォーム送信時に空欄を確認・空欄の色を変更</title>
<script language="JavaScript">
<!--
function check() {
err = 0;
for(i = document.form1.length - 1 ; i >= 0 ; i--) {
with(document.form1.elements[i]) {
if(value == "") {
err++;
focus();
style.borderColor = "#f00";
style.background = "#fee";
}
else {
style.borderColor = "#999";
style.background = "#fff";
}
}
}
if(err > 0) {
alert("すべての欄に入力してください");
return false;
}
}
function res() {
return confirm("すべての欄を削除します。\nよろしいですか?");
}
//-->
</script>
<style type="text/css">
<!--
input, textarea {
background: #fff;
border: solid 1px #999;
}
//-->
</style>
</head>
<body>
<form name="form1" action="../../sample/sample.cgi"
method="post" onSubmit="return check()" onReset="return res()">
名前<br>
<input type="text" name="name" size="50"><br>
<br>
メールアドレス<br>
<input type="text" name="mail" size="50"><br>
<br>
本文<br>
<textarea name="text" cols="50" rows="10"></textarea><br>
<br>
<input type="submit" value=" 送 信 ">
<input type="reset" value=" リセット ">
</form>
</body>
</html>
〔 実行する 〕