我有一长串从数据库中的数据创建的输入字段,或多或少像这样:
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 -->
}