0

my problem has 2 sides to it.

I am trying to send a simple get value that is generated via a loop like so:

    for(var x=0; x<del.length; x++) {
        del[x].onclick = function () {
        WORK(x);
        }
    }

Here is my frustrated WORK function

   function WORK (x) {
        var y = ids[x];
        var url = "Delete.php?val=" + y;
        window.location = url;
    }

I know i just have to pass the value to the function...but if i set it up like that the page executes the function on load and doesn't wait for my click and as is it is now it will always pass an undefined value...what is going on here?

Blaze Blue
  • 15
  • 1
  • 3
  • 1
    What is `del`? Is it a collection of DOM nodes? It would be useful to see some HTML and some of the other code. The big thing is you're always going to have `x` as the last value for all clicks due to scoping issues. – Andy Apr 25 '16 at 11:58
  • as pointed out by @Andy you will always get x as last value, you need to use clousre inside a anonymous function, to bind your data correctly on click event , there are lot of article on this topic – user3045179 Apr 25 '16 at 12:01
  • well it's a collection of all the td's with the class name delete, basically i wanted to make delete buttons that send a value with the row id via GET, i know ajax can do this better but this seemed more fun :o. – Blaze Blue Apr 25 '16 at 12:05
  • Use event delegation instead. Attach an event listener to `` and catch the events from the buttons as they bubble up the DOM. Simpler and you're using listeners sparingly
    – Andy Apr 25 '16 at 12:08
  • @BlazeBlue, [here's a quick example of event delegation wrt your example](https://jsfiddle.net/Lnjxnkg0/1/). – Andy Apr 25 '16 at 12:19

1 Answers1

0

Variable hoisting + non-scoped variables in for loops. Use .forEach:

Array.prototype.slice.call(del).forEach(function(elem, index) {
    elem.onclick = ...
});

Or if you can't, use an immediately-invoked anonymous function:

for (var x = 0; x < del.length; x++) {
    (function() {
        var elem = del[x];
        ...
    })();
}

When you iterate through the loop, there is only ever one x variable. It is not scoped to the for loop, and changes on each iteration (x++). When you trigger a click, the event handler is called, which in turn calls WORK with the value of x as an argument, which would've already been del.length by the time it runs.

wilsonzlin
  • 2,154
  • 1
  • 12
  • 22