2

html

<button id="test1" onclick="getclickname(); return false;">click</button>

javascript (it's showing "Undefined")

   function getclickname()
   {
   alert(this.id);
   }

i dont want code like this

<button id="test1" onclick="alert(this.id);">click</button>

call getclickname is needed, thanks guys

DREAM
  • 426
  • 2
  • 14

4 Answers4

3

You have to pass corresponding argument to the function.

  1. You need to pass button object to onclick function to get the id of button.

function getclickname(obj)
    {
      //By passing object as argument you can access all properties of that element
      alert(obj.id);
      alert(obj.className);
    }
<button id="test1" onclick="getclickname(this); return false;" class="test_1">click</button>
  1. You can directly pass this.id as well as an argument

function getclickname(id) {
  alert(id);
}
<button id="test1" onclick="getclickname(this.id); return false;">click</button>

Note:

  • A bit code modification is instead of return false; you can add return before function name and that will do the same thing. like :- onclick="return getclickname(this.id);"

  • By passing object as argument you can access all properties of that element (check first code sample modification).

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
2

Please try the below code. It's working for you.

Use class for click event in button.

<button id="test1" class="test-btn" >click</button>

Use the below click event function to get id after click.

$('.test-btn').click(function() {
  var id = $(this).attr('id');
  alert(id)
});
Mukesh Singh Thakur
  • 1,335
  • 2
  • 10
  • 23
1

Hope this Helpful...

view

onclick="return getclickname(this);"

js

function getclickname(these)
{
   alert(these.id);
}
Antony Jack
  • 480
  • 2
  • 16
1

Use like this

<button id="test1" onclick="getclickname(this); return false;">click</button>
<script>
   function getclickname(e)
   {
   alert(e.id);
   }
</script>
Vinil Vinayan
  • 101
  • 1
  • 4