0

Let's say i have a button. <input type="button" value="Click me" onClick="MyFuncion()">
In the function, I want to get the button object.
I tried the following:

function MyFunction()
{
  this.value = "Another text";
}
<input type="button" value="Click me" onClick="MyFuncion()">

My intent was changing the button's text to something another text.
As you can see, this isn't pointing to the button. My guess is that it is pointing to the function itself.
How do i do this?

In a few words, my question is: How do i get the object that called a function?

  • you have a typo in onclick : `MyFuncion`, you could also add param `e` to your function, and see `e.target` [doc](https://developer.mozilla.org/en-US/docs/Web/API/event.target) – Hacketo Feb 20 '15 at 15:01
  • Here is your answer :) http://stackoverflow.com/questions/1553661/how-to-get-the-onclick-calling-object – bbialas Feb 20 '15 at 15:04
  • Or you can call `onClick="MyFuncion.apply(this)"` – Simon Feb 20 '15 at 15:04
  • @TheSuperCuber oh don't feel bad; there's nothing wrong with duplicate questions. If anything, having a variety of text for searching helps everybody. Sometimes I only know there's a duplicate because I happen to have seen the question before. That other question has some good answers. If you still feel the need for more help, you can ask another, more specific question! – Pointy Feb 20 '15 at 18:21

2 Answers2

2

The "this" context is available when you call the function from the onclick attribute, you can pass it into your function like this:

function MyFunction(button)
{
  button.value = "Another text";
}
<input type="button" value="Click me" onclick="MyFunction(this)">

The "this" context in your function will be either "window" or, if you're in strict mode, null. This is because the function was called as a function and not as a method.

Thomas Parslow
  • 5,712
  • 4
  • 26
  • 33
1

pass this into MyFunction.

<input type="button" value="Click me" onClick="MyFunction(this)">

function MyFunction(el) {
    el.value = "Another text";
}
Joe Fitter
  • 1,309
  • 7
  • 11