sudobangbang
sudobangbang

Reputation: 1456

How to determine which button called a function?

How would I know which button caused this function to run? Specifically, if I want to set the value of the function to be equivalent to the value of the button?

var foo_button = document.getElementById("foo_button");
var bar_button = document.getElementById("bar_button");
foo_button.onclick = foo_or_bar;
bar_button.onclick = foo_or_bar;

Then in a function later on:

function foo_or_bar(){

    //this should return the value of the button that was pressed (in this case "foo" 
    //or "bar"
    return button_that_sent_me;

}

Is there a way I can detect the value of which button caused this to occur?

Upvotes: 0

Views: 3143

Answers (2)

Alien Life Form
Alien Life Form

Reputation: 581

You can use this as @A1rPun says or access the button through window.event, which also helps when you use inline onclicks, and other unrecommended practices:

JS

function foo_or_bar() {
  console.log(window.event.target.value);
  console.log(this.value);
}

HTML

<button id="foo_button" value="foo">internals</button>

Gives you the following console log:

foo
foo

Upvotes: 1

Evadecaptcha
Evadecaptcha

Reputation: 1441

'this' sends all information associated with the element fire the event:

<button onclick="foo_or_bar(this.id);" id="foo">Foo</button>

function foo_or_bar(id) {
    button_that_sent_me = id;
}

Upvotes: 0

Related Questions