Reputation: 43
i have a button:
<button id="my-button" type="button" onclick="action()">press me</button>
i want to get the id of the button ("my-button"), in the "action" function.
i tried to get it with:
var id = $(this).id;
var id = $(this).attr('id');
i tried to send the object from the dom:
<button id="my-button" type="button" onclick="action(this)">press me</button>
and it didn't work...
how can i get the id?
Upvotes: 2
Views: 8534
Reputation: 1
event.target gives the element associated with the event, click in your case.
$(".btn-send").click((e)=>{
$this = jQuery(e.target); // e.target gives element associated (targeted) with this event (click)
console.log($this.data('id')); // loging data id for demo purpose
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="button" value="Send message" class="btn-send" data-id="40" />
Upvotes: 0
Reputation: 133453
You need to accept the parameter
function action(elm) {
alert(elm.id)
}
<button id="my-button" type="button" onclick="action(this)">press me</button>
However, as you are using jquery I would recommend you to bind events using it.
$(function() {
$('#my-button').on('click', function() {
alert(this.id);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="my-button" type="button">press me</button>
Upvotes: 6
Reputation: 19007
Set the onclick event in your jquery code, Right now what ever is doing is old style, and is deprecated in few browsers (many in mobile browsers).
So remove the binding's of onlclick event from your HTML element and add in jquery as shown below.
$(function() { //document ready event
$('#my-button').on('click',function() {
var id = $(this).attr('id');
alert(id);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="my-button" type="button">press me</button>
Upvotes: 3
Reputation: 797
<button id="1" onClick="reply_click(this.id)">Button</button>
<script type="text/javascript">
function reply_click(clicked_id)
{
alert(clicked_id);
}
</script>
Upvotes: 0