我有一个基本的验证功能和一个addEventListener附加到select元素。现在,该函数不仅不会在事件发生时触发,而且还会在页面加载时触发。你能帮我找出原因吗?
元素是:
<select name="VisitSchedLocation" id="VisitSchedLocation" size="1">
<option value="">Choose a location for this visit</option>
<option value="1">Location 1</option>
...
</select>
addEventListener为:
document.getElementById('VisitSchedLocation').addEventListener('blur', validateVisitSchedLocation());
最后,函数:
function validateVisitSchedLocation() {
if (VisitSchedLocation.options[VisitSchedLocation.selectedIndex].value == '') {
alert('Location must be selected!');
return false;
};
}
任何帮助将不胜感激。
最佳答案
Working DEMO
您正在调用/调用函数,而不是将其附加到事件:
document.getElementById('VisitSchedLocation').addEventListener('blur', validateVisitSchedLocation());
而是这样做(不带括号):
document.getElementById('VisitSchedLocation').addEventListener('blur', validateVisitSchedLocation);