I have this HTML form which works fine when written like this:
我有这样的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>
But when I change 3rd and 4th line to:
但是,当我将第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 doesn't work! How could it be? After all i just changed the name and ID?
,onblur不起作用!怎么会这样?毕竟我只是更改了名称和ID?
This is my validateName(name) function:
这是我的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;
}
}
thanks
1 个解决方案
#1
You need to change ID of error element too (because of x + Error
).
您还需要更改错误元素的ID(因为x +错误)。
<span id="firstnameError"...>
And put function params into quotes:
并将函数参数放入引号:
<input type="text" name="firstname" id="firstname" onblur="validateName('firstname')" />
#1
You need to change ID of error element too (because of x + Error
).
您还需要更改错误元素的ID(因为x +错误)。
<span id="firstnameError"...>
And put function params into quotes:
并将函数参数放入引号:
<input type="text" name="firstname" id="firstname" onblur="validateName('firstname')" />