0

Is it possible to dynamically acquire the name of the element that calls a function with the onClick event?

I need to write a code to reuse massively in a form to validate the content.

jchamp
  • 172
  • 3
  • 11
J.Amaru
  • 5
  • 4
  • Possible duplicate of [How to get the onclick calling object?](http://stackoverflow.com/questions/1553661/how-to-get-the-onclick-calling-object) – Mr Lister Oct 05 '15 at 11:01

3 Answers3

0

It's a little tough to say this is exactly what you are looking for, but something like this?

onClickHandler(event) {
  var domNode = event.targetElement;
  var name = domNode.getAttribute("name");
  // do what you will with that
}

Getting the element this way makes sure it was what you clicked on - using this can be different depending on if you bound scope to the method along the way somewhere

josh.trow
  • 4,861
  • 20
  • 31
  • If you set `onClickHandler` with `addEventListener` then `this` will point to `targetElement`. – VisioN Oct 05 '15 at 11:01
0

Let me answer with an example if this is what you are looking for:

Html:

<input name='Foo" type='button' value='Click Me' onclick='bar(this)'>

JS:

function bar(elem) {
    alert('Clicked by' + elem.name);
}

You can use parentNode to navigate in your form.

flowit
  • 1,382
  • 1
  • 10
  • 36
0

Yes you can do this by passing an event to the respective onClick function as stated below.

<a href="#" id="testLink" onclick="HandleLink(event)">Link</a>

function HandleLink(event)
{
    var x = event.target;
    alert(x.id);
}
J-D
  • 1,575
  • 1
  • 11
  • 22