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
4 Answers
Reset to default 3You have to pass corresponding argument to the function.
- You need to pass button object to
onclick
function to get theid
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>
- 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 addreturn
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>