0

I've got a simple function that does basically nothing but alert me of the validity:

function alertV(elem) {
    alert("here");
    alert(elem.checkValidity());
    alert("really");
}

The code for hooking this up:

var elements = document.forms["form"].getElementsByTagName("input");
for (i = 0; i < elements.length; i++) {
    elements[i].onkeyup = function () { alertV(elements[i]) };
}

Here shows up fine, but checkValidity() isn't doing anything and is even causing the really call to be ignored. Am I passing in the arguments wrong? I essentially just want this, which works:

<input type="text" onkeyup="alertV(this);">

idlackage
  • 2,715
  • 8
  • 31
  • 52

1 Answers1

1

Try using a closure:

elements[i].onkeyup = (function (a)
{
    return function ()
    {
        alertV(elements[a])
    }
})(i);
Justin Morgan - On strike
  • 30,035
  • 12
  • 80
  • 104
Royi Namir
  • 144,742
  • 138
  • 468
  • 792
  • Edited because [IIFEs](http://benalman.com/news/2010/11/immediately-invoked-function-expression/) need to be wrapped in parentheses. – Justin Morgan - On strike Sep 10 '13 at 15:26
  • They are mandatory, at least in some JS engines (and possibly all of them). JS requires the parentheses in order to interpret a function declaration as an expression. Tested just now in the Chrome JS console with `function(i){console.log(i);}('test');` and `(function(i){console.log(i);})('test');` – Justin Morgan - On strike Sep 10 '13 at 15:32
  • @JustinMorgan there is a difference between declaration and expression. – Royi Namir Sep 10 '13 at 15:34
  • That was originally my point; when the IIFE is the entire statement, the parentheses are what tell JS to interpret it as an expression, not a declaration. BUT...I've tested it again, and you're right: `var k = function(i){return i;}('test');` does work. I guess the assignment operator is a hint that what follows is an expression. My mistake, sorry about that. – Justin Morgan - On strike Sep 10 '13 at 15:41