Reputation: 9445
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?
Upvotes: 1
Views: 2758
Reputation:
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>
Upvotes: 1
Reputation: 2126
function f1(element)
{
alert($(element).attr("id"));
if ($(element).is(":button")) {
alert("Im button");
}
}
<input type="submit" id="btn2" onclick="f1(this)"/>
Upvotes: 2
Reputation: 9174
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
Upvotes: 1
Reputation: 2673
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);
}
Upvotes: 1
Reputation: 388446
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
Upvotes: 4
Reputation: 28773
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);
}
Upvotes: 2