我有这样的HTML表单,在这样写的时候工作正常:
<fieldset>
<label for="name">Name</label>
<input type="text" name="name" id="name" onblur="validateName(name)" />
<span id="nameError" style="display: none;">You can only use alphabetic characters, hyphens and apostrophes</span>
</fieldset>
但是当我将第3和第4行更改为:
<input type="text" name="firstname" id="firstname" onblur="validateName(firstname)" />
<span id="firstnameError" style="display: none;">You can only use alphabetic characters, hyphens and apostrophes</span>
,onblur不起作用!怎么会这样?毕竟我只是更改了名称和ID?
这是我的validateName(name)函数:
function validateName(x) {
// Validation rule
var re = /[A-Za-z -']$/;
// Check input
if (re.test(document.getElementById(x).value)) {
// Style green
document.getElementById(x).style.background = '#ccffcc';
// Hide error prompt
document.getElementById(x + 'Error').style.display = "none";
return true;
} else {
// Style red
document.getElementById(x).style.background = '#e35152';
// Show error prompt
document.getElementById(x + 'Error').style.display = "block";
return false;
}
}
感谢
答案 0 :(得分:2)
您还需要更改错误元素的ID(因为x + Error
)。
<span id="firstnameError"...>
将函数参数放入引号:
<input type="text" name="firstname" id="firstname" onblur="validateName('firstname')" />