データベース内のデータから作成された入力フィールドの長いリストがあります。多かれ少なかれ次のようになります。
foreach ($data as $value) {
...
<input type="text" name="date_earned$row" id="date_earned$row" value = "$date_earned" onchange="changeDate(this)">
...
}
onchange スクリプトは次のようになります (注: 日付は標準の日付ではないため、通常の日付を検証しようとしているわけではありません)。エラーが発生した場合、変更したばかりの要素にフォーカスを戻すことはできません。フォーカスを別の要素に設定しても問題ありません。なんで?
<script type="text/javascript">
function changeDate(sel) {
var theDate = sel.value;
var isValid = true;
if (theDate) {
<!-- .... some stuff in here to validate the date, sets isValid = false if it is not correct format} -->
}
if (!(isValid)) {
<!-- ... do some stuff in here to display the error message -->
document.getElementById('thiselementsid').focus(); <!-- this doesn't work when 'thiselementsid' is the id of the element which just lost focus-->
document.getElementById('someotherelement').focus(); <!-- this works, but not if 'someotherelement' is the id of the last focused element -->
}