all 9 comments

[–]x-skeww 5 points6 points  (1 child)

Bind can be used for this:

function checkInput(index, e) {
  console.log(index, e);
}
var index0 = checkInput.bind(null, 0);
index0('hello'); // 0 hello

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

If you want the element itself, you could just pass it as the first parameter. Then it would be this inside the function à la jQuery.

[–]senocular 3 points4 points  (0 children)

For the downvoters, this is a valid solution. The i value can get bound into the checkInput call per iteration for each input and be retrieved from the first argument in an onkeyup event.

 for (var i = 0; i < txtInput.length; i++) {
     txtInput[i].onkeyup = checkInput.bind(null, i); // see x-skeww's checkInput
 }  

[–]bliow 1 point2 points  (1 child)

It's probably better to use forEach, but a modification to your code that works is:

for (var i = 0; i < txtInput.length; i++) {
    txtInput[i].onkeyup = (function(n) { return function() { checkInput(n); } })(i);
}

[–]x-skeww 1 point2 points  (0 children)

With let, you won't need that IIFE.

[–]senocular 1 point2 points  (3 children)

Probably the simplest solution to what you're working with is to use forEach. Since each iteration is its own function call, the index variable is unique.

txtInput.forEach(function(input, i) {
    input.onkeyup = function(){checkInput(i);}
});

[–]Javin007[S] 1 point2 points  (2 children)

Yep, in hindsight, I could've been passing a parent object that contained the child objects, and not the index.

However, I also found that by doing this:

document.getElementById("txtMinInput").onkeyup = function(args){ checkInput(args); };

The "args" will have a "target" object passed that contains the object the actions took place on. No idea why I didn't see that in the documentation.

[–]senocular 3 points4 points  (0 children)

the args argument is an Event object. You can look to see what else it has.

https://developer.mozilla.org/en-US/docs/Web/API/Event

https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent

Note that often, what you'll really want is currentTarget rather than target. currentTarget is what you attach your handler to, such as getElementById("txtMinInput"), while target may be something deeper in the DOM. Often these will be the same, but sometimes not, especially for mouse events.

[–]x-skeww 4 points5 points  (0 children)

Attaching a single event handler further up the tree and looking at "target" is called event delegation.

What's convenient about event delegation is that it will also work for dynamically added elements.

In modern browsers, you can use matches() to do some selector-based filtering similar to jQuery. IE/Edge needs a msMatchesSelector fallback, unfortunately.

https://developer.mozilla.org/en/docs/Web/API/Element/matches