2

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?

4 Answers 4

6

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 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>

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

Comments

3

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>

Comments

0
<button id="1" onClick="reply_click(this.id)">Button</button> <script type="text/javascript"> function reply_click(clicked_id) { alert(clicked_id); } </script> 

Comments

0

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" />

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.