The Nuthouse
The Nuthouse

Reputation: 173

"Target not defined" error when trying to get target of event listener

I'm trying to calculate triangles, and I'm trying out my code right now so I need to make an algorithm to calculate the triangles instead of having it hard-coded. I need to find grab the target of an event listener but target isn't working and I don't know why or how to fix it. The target refers to the aV && a before the event listener which are both input fields.

function calc(){
    if (target.value.length > 0){
        console.log("hooray");
    };
};

aV && a.addEventListener("keydown", function(ev){
    if(ev.keyCode == 13){
        calc();
    };
});

Upvotes: 0

Views: 225

Answers (3)

Mick
Mick

Reputation: 79

The function that handles the event should be like this:

function calc_keydownHandler(e){
var target = e.target;
//do something with the target now
}

Because you've got a argument of target the reference would be target.target which doesn't make sense.

Upvotes: 0

Mamun
Mamun

Reputation: 68923

You can loop through them with forEach(). You also have to pass the target the calling function.

function calc(target){
  if (target.value.length > 0){
    console.log("hooray");
  };
};

[aV, a].forEach(function(el){
  el.addEventListener("keydown", function(ev){
    if(ev.keyCode == 13){
      calc(ev.target);
    };
  });
});

Upvotes: 1

Jack Bashford
Jack Bashford

Reputation: 44125

That entire addEventListener statement is a conditional which is the equivalent of going:

true && true;

It does nothing. Add an if statement (also make sure you're passing ev.target into calc as an argument:

function calc(target){
    if (target.value.length > 0){
        console.log("hooray");
    };
};

if (aV) {
    a.addEventListener("keydown", function(ev){
        if(ev.keyCode == 13){
            calc(ev.target);
        };
    });
}

Upvotes: 1

Related Questions