-1

I have to catch the event.target.value in a handler. But my function takes another parameter along with event parameter. That's why it doesn't get the event.target. It returns undefined. So how can I find event.target if I have another parameter along with?

function a(e, b) {
  console.log(e.target.value);
  return e.target.value + b;
}

var input = document.querySelector('#input');

input.addEventListener('click', function() {
  a(4);
});
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
<input id="input" type="submit" value="5">
</body>
</html>
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Imran
  • 440
  • 4
  • 15

1 Answers1

1

Just accept it in the event listener, and pass it to your function:

input.addEventListener('click', function(e) {
  a(e, 4);
});

With this code, the return in a is useless, though, since the value isn’t captured anywhere. You’d need to use that return value somehow, e.g. by logging it with console.log(a(e, 4));.

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
  • 1
    Come on this is a duplicate question! `(:` – Ele Jul 31 '18 at 14:06
  • @Ele The connection of this question to the dupe target isn’t _that_ clear to me, and likely even less so for the OP. The OP doesn’t need to add an `addEventListener` wrapper or something similar, as in the other question. – Sebastian Simon Jul 31 '18 at 14:11
  • The OP only needs to understand how to get the event object and how to pass it to his/her own function. – Ele Jul 31 '18 at 14:15