سؤال

I have a basic validation function and a addEventListener to attach to a select element. Now, not only doesn't the function fire when during the event, but it fires on pageload. Can you please help me figure out why?

The element is:

<select name="VisitSchedLocation" id="VisitSchedLocation" size="1">
  <option value="">Choose a location for this visit</option>
  <option value="1">Location 1</option>
  ...
</select>

The addEventListener is:

document.getElementById('VisitSchedLocation').addEventListener('blur', validateVisitSchedLocation());

And, finally, the function:

function validateVisitSchedLocation() {
  if (VisitSchedLocation.options[VisitSchedLocation.selectedIndex].value == '') {
    alert('Location must be selected!');
    return false;
  };
}

Any help would be greatly appreciated.

هل كانت مفيدة؟

المحلول

Working DEMO

You are calling/invoking the function rather than attaching it to event:

document.getElementById('VisitSchedLocation').addEventListener('blur', validateVisitSchedLocation());

Instead do this (No parentheses):

document.getElementById('VisitSchedLocation').addEventListener('blur', validateVisitSchedLocation);
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top