My alert happens on pageload instead of waiting for the onblur event

Hi, I’m trying to write a script grabs all inputs on a page and listens for an onblur event. Pretty simple right? Consider the following code:


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
  <meta http-equiv="content-type" content="text/html; charset=windows-1250">
  <meta name="generator" content="PSPad editor, www.pspad.com">
  <title></title>
  <script type="text/javascript">
    window.onload = function() {
      var r = document.getElementsByTagName('input');
      for(var i = 0; i<= r.length; ++i) {
        r[i].onblur = alert('this one =' + i );  
      }
    }   
  </script>
  </head>
  <body>
  
  <input type="text" />
  <input type="text" />
  <input type="text" />

  </body>
</html>



This code runs through and alerts out for all 3 inputs on pageload. Why is this? I need it to wait until the element loses focus before the alert is alerted.

You’re looping in the onload event, and trying to assign the return value of of calling the alert() function. You can create an anonymous function, that when called, will call alert, and assign that anonymous function instead.


      for(var i = 0; i<= r.length; ++i) {
        r[i].onblur = function() {
            alert('this one =' + i );
        }
      }

But you’ll come across another wonder, and that’s because you created a closure around the i variable(you can read more on closures).


      function createMyEventHandler(num) {
          return function() {
              alert('this one =' + num );
          }
      }
      for(var i = 0; i<= r.length; ++i) {
        r[i].onblur = createMyEventHandler(i);
      }

Hi crmalibu, Yes that’s it, thanks.

I’m aware of closures…it’s a bit of a grey area for me. I’ve been reading about them but I haven’t yet wrapped my head around it. I know it preserves state after a function has returned but it’s still not completely gelling with my brain.

Must do some more reading and testing in to this one.

Many thanks for your reply :slight_smile: