Home > Software engineering >  How to Select all buttons and alert their respective name when CLICKED in jQuery
How to Select all buttons and alert their respective name when CLICKED in jQuery

Time:11-18

<body>
    
    <h1 >jQuery</h1>
    <div >
        <button name="up_button" id="upB" ></button>
        <button name="left_button" id="leftB" ></button>
        <button name="right_button" id="rightB" ></button>
        <button name="down_button" id="downB" ></button>
    </div>
    

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script >
        $("button").on("click", function(){
        var buttonClicked = $("button").attr("name");
        alert("Button CLicked: "   buttonClicked);
        }) 
    </script>
</body>

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

CodePudding user response:

you are already calling the $("button") as eventlistener. Instead of calling another $("button") in variable initialization, use $(this)

 var buttonClicked = $(this).attr("name");

$("button").on("click", function(){
  var buttonClicked = $(this).attr("name");
  alert("Button CLicked: "   buttonClicked);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<h1 >jQuery</h1>
<div >
    <button name="up_button" id="upB" ></button>
    <button name="left_button" id="leftB" ></button>
    <button name="right_button" id="rightB" ></button>
    <button name="down_button" id="downB" ></button>
</div>

CodePudding user response:

<body>
    
    <h1 >jQuery</h1>
    <div >
        <button name="up_button" id="upB" >A</button>
        <button name="left_button" id="leftB" >B</button>
        <button name="right_button" id="rightB" >C</button>
        <button name="down_button" id="downB" >D</button>
    </div>
    

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script >
        $("button").on("click", function(e){
        var buttonClicked = $("button").attr("name");
                console.log(e.target.name)
        }) 
    </script>
</body>

Just need to have the event handler with event argument, and use event.target.valueto get the value of button that is clicked.

CodePudding user response:

try this:

$(".buttonClass").on("click", function (event) {
    var buttonClicked = event.target.name;
    alert("Button CLicked: "   buttonClicked);
  });

CodePudding user response:

$("button").on("click", function(){
     var buttonClicked = $(this).attr("name");
     alert("Button CLicked: "   buttonClicked);
}) 

$(this) will select the object of clicked button

  • Related