$("button").on("click", function(){
var buttonClicked = $("button").attr("name");
alert("Button CLicked: " + buttonClicked);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<h1 class="titleClass">jQuery</h1>
<div class="buttonClass">
<button name="up_button" id="upB" class="upDown"></button>
<button name="left_button" id="leftB" class="leftRight"></button>
<button name="right_button" id="rightB" class="leftRight"></button>
<button name="down_button" id="downB" class="upDown"></button>
</div>
I want to display the name (as alert or console.log) when a button is clicked from the above list
$("button").on("click", function(){
var buttonClicked = $("button").attr("name");
alert("Button CLicked: " + buttonClicked);
})
4
Answers
Just need to have the event handler with event argument, and use
event.target.value
to get the value of button that is clicked.try this:
you are already calling the
$("button")
aseventlistener
. Instead of calling another$("button")
in variable initialization, use$(this)
$(this) will select the object of clicked button