Reputation: 7523
I have a simple JavaScript
function, which I am trying to get the ID of the element I used to initiate the function. My element is a simple DIV
:
<script type="text/javascript" >
function updateProduct(prod_id,old_q){
alert(jQuery(this).attr('id'));
}
</script>
<div id="button_container" style="float:left; margin-right:7px; margin-top:3px; width:59px; height:20px; cursor:pointer;" onClick="updateProduct('19','3060');">
There are other HTML elements on this page (of course), but this is a test button for now, and no other elements have the same test ID I have here called button_container
. Also my Script
is stand alone just as you see. It's not part of a longer Script
etc.. Am I missing something super simple? The alert returns "Undefined" and the Console
doesn't report any warnings or errors...
Upvotes: 0
Views: 652
Reputation: 18569
You need to pass the element object.
<script type="text/javascript" >
function updateProduct(obj, prod_id,old_q){
alert(jQuery(obj).attr('id'));
}
</script>
<div id="button_container" style="float:left; margin-right:7px; margin-top:3px; width:59px; height:20px; cursor:pointer;" onClick="updateProduct(this, '19','3060');">
Upvotes: 0
Reputation: 160953
The this
in your function is the global object window
.
You need to pass it to the function.
function updateProduct(prod_id,old_q, element){
alert(element.id);
}
<div id="button_container" onClick="updateProduct('19','3060', this);">
Upvotes: 2