1

I have a Simple JavaScript Function:

function f1() { alert("HI"); } 

I'm calling the same Javascript function from two places, say:

<input type="submit" id="btn1" onclick="f1()"/> <input type="submit" id="btn2" onclick="f1()"/> 

How to find the target element which called this Function?

EDIT: How to check if the element is a button or some other?

1
  • If you're using jquery, what's the point of inline javascript? Use $(#btn1).click(...). Commented May 22, 2013 at 11:43

6 Answers 6

4

HTML

<input type="submit" id="btn1" onclick="f1(this)"/> <input type="submit" id="btn2" onclick="f1(this)"/> 

Js

function f1(el) { console.log(el) } 

Demo: Fiddle

Sign up to request clarification or add additional context in comments.

Comments

2

Try with this

<input type="submit" id="btn1" onclick="f1(this)"/> <input type="submit" id="btn2" onclick="f1(this)"/> 

and console like

function f1(comp) { console.log(comp); } 

Comments

2
function f1(element) { alert($(element).attr("id")); if ($(element).is(":button")) { alert("Im button"); } } <input type="submit" id="btn2" onclick="f1(this)"/> 

1 Comment

How to check if the element is a button or some other?
1

Easiest way:

<input type="submit" id="btn1" onclick="f1(this)"/> <input type="submit" id="btn2" onclick="f1(this)"/> 

JS:

function f1(btn) { alert("Hi from " + btn); } 

Comments

1

Add this to the function call

<input type="submit" id="btn1" onclick="f1(this)"/>

<input type="submit" id="btn2" onclick="f1(this)"/>

And modify your js as

function f1(el) { alert(el.nodeName) ; // alerts type of HTML element } 

el will contain a reference to the element

EDIT : added code to detect type of HTML element

Comments

1

If you are already using jquery on your page, maybe you should try giving all the elements that you want to target a shared class and then detect the clicks?

<input class="same_kind_buttons" type="submit" id="btn1" /> <input class="same_kind_buttons" type="button" id="btn2" /> <script> $(".same_kind_buttons").click(function() { console.log($(this).attr("type")); console.log(this.id); }); </script> 

Of course if your'e not using jquery on the page you shouldn't include it just for that function and you can use :

<input type="submit" id="btn1" onclick="f1(this);"/> <input type="submit" id="btn2" onclick="f1(this);" /> <script> function f1(elem) { console.log(elem.tagName); console.log(elem.id); } </script> 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.