最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - get id of button by clicked with function - Stack Overflow

programmeradmin5浏览0评论

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

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

Share Improve this question asked Mar 11, 2020 at 5:08 DREAMDREAM 4264 silver badges16 bronze badges 3
  • Better to avoid inline handlers entirely – CertainPerformance Commented Mar 11, 2020 at 5:09
  • if you didn't pass argument then how to get in alert... alert(this.id); – Antony Jack Commented Mar 11, 2020 at 5:10
  • Inside button onclick="getclickname(this.id)" and function getclickname(buttonId) { alert(buttonId);} – Not A Robot Commented Mar 11, 2020 at 5:12
Add a ment  | 

4 Answers 4

Reset to default 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).

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)
});

Hope this Helpful...

view

onclick="return getclickname(this);"

js

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

Use like this

<button id="test1" onclick="getclickname(this); return false;">click</button>
<script>
   function getclickname(e)
   {
   alert(e.id);
   }
</script>
发布评论

评论列表(0)

  1. 暂无评论