What is the method to retrieve the name of a clicked button using JavaScript?

There are 2 <div> elements containing a minimum of 81 buttons each, all having the same class. However, they have unique ids and names. I am currently experimenting with ways to display an alert message showing the name of the button that is being pressed.

Answer №1

function logElementId(element){
  return function(){
    console.log(element.getAttribute("id"));
  }
}

var buttons = document.getElementsByClassName("myButton")
Array.prototype.forEach.call(buttons, function(btn){
  btn.onclick = logElementId(btn);
})
<button id="a1" class="myButton">A1</button>
<button id="b2" class="myButton">B2</button>

Answer №2

Retrieve all buttons with the same class name and add a click event listener to each button, ensuring that when a button is clicked, the listener is activated:

function buttonClickListener(){
 console.log(this.id + " " + this.name);
}

var allButtons = document.getElementsByClassName('myButton');
for(i=0; i<allButtons.length; i++){
   allButtons[i].addEventListener('click', buttonClickListener);
}
<button id="1" class="myButton" name='name1'>B1</button>
<button id="2" class="myButton" name='name2'>B2</button>
<button id="3" class="myButton" name='name3'>B2</button>
<button id="4" class="myButton" name='name4'>B2</button>
<button id="5" class="myButton" name='name5'>B2</button>

Answer №3

If you want to achieve this, you can utilize the this.name property within the click event handler function:

var buttons = document.querySelectorAll('button');
buttons.forEach(function(button){
  button.addEventListener('click', function(){
    console.log('The name of the clicked button is:', this.name)
  })
})
<div>
  <button type="button" id="btn1" name="btnName1">Button 1</button>
  <button type="button" id="btn2" name="btnName2">Button 2</button>
 
  <!--------- More Buttons--------->
</div>
<div>
  <!--------- More Buttons--------->
 
  <button type="button" id="btn48" name="btnName48">Button 48</button>
  <button type="button" id="btn49" name="btnName49">Button 49</button>
  <button type="button" id="btn50" name="btnName50">Button 50</button>
  
  <!--------- More Buttons--------->
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Encountering a hiccup in executing map.reduce

var mapFunction1 = function() { for (var i = 0; i < this.money.length; i++) { emit("balance", this.money[i].amount); } }; var reduceFunction1 = function(keyBalance, valuesBalance) { return Array.sum(valuesBalance); }; db.users.ma ...

Is there a method to compress all of my JS/CSS files before displaying them in the browser without doing so while editing them in the IDE?

I have a JavaScript file with numerous comments and unnecessary spaces, making it larger and slowing down the website. I am seeking a solution to minify the file when starting the server, while still being able to edit the original file in my IDE. Essen ...

Using an array as a constant within a PHP class

Similar Inquiry: Is it viable to define an array as constant? Can an array be utilized as a class constant within PHP? For example: const MYARRAY = array('123', '234'); If not, what is the reason for this limitation? ...

Setting the default value for a dropdown in Angular 2 using Kendo UI

I'm currently facing an issue with creating a dropdownlist using Kendo UI. The problem arises when I try to set a default selected value upon loading the screen. Referring to their documentation, my code is structured like this: HTML: <kendo-drop ...

Encountering an issue in Laravel when trying to retrieve data using relationships and the paginate() method

When I try to fetch data using paginate(10), Vue.js does not work. However, if I use paginate(5), it works fine. The code in the Controller with relationships in the model files is working fine and returns a 200 OK response. $results = Posts::with([' ...

Leveraging the spread operator for setting state in a series of consecutive updates

Within my component, I am retrieving values from local storage and attempting to load them into the state when the component mounts. However, only the last property that I add seems to be included in the state. I have confirmed that all values are present ...

Refreshing a web page in Internet Explorer can cause the HTTP Header content to be altered

As I monitor my dashboard retrieving continuous data from an SAP server, I stumbled upon a solution to fetch the current server date. This approach allows me to display when the dashboard was last updated, and this date is displayed in the DOM. //Method f ...

Dealing with cascading jQuery deferred callsHere are some guidelines on

When I have a function that needs to retrieve data and return a promise, I often find myself making multiple requests one after another. This results in nested deffered calls where the last call resolves on the deferred object that the function ultimatel ...

Ensuring data integrity with form validation using Jquery prior to submitting an

After researching various forums and referencing one, I am still unable to find a solution for my issue. My query is: When I click a button, it triggers a function that includes validation. Upon successful validation, I attempt to post data with an Aj ...

Employing AJAX, execute a synchronous function asynchronously (Javascript)

Here's a code snippet for the sync function. I've been calling it inside an Ajax, but apparently it's deprecated because it's synchronous. Is there any way to make it run as if it were asynchronous? Or is there a way to convert it into ...

The HTML pattern [A-Za-z] specifies that the entered name must adhere to the required format, such as inputting "john"

<div class="title details"> <label for="idtitle" class="label">Title</label> <input type="text" placeholder="Title" id="idtitle" pattern="[A-Za-z]" required> </div> Link to Firefox screenshot ...

Assistance needed for iterating through JSON data

I need assistance retrieving specific data from a JSON response in my JavaScript code. Unfortunately, the current approach is not providing the desired results: This is my JavaScript code snippet: function retrieveArtists(response){ var artistList ...

what is the best way to display a chosen value in a dropdown menu using jQuery?

How can I display a value from a database in a select option? This code is written in PHP, JSON, AJAX, and JQUERY. $(document).on('click', '.edit_data', function () { var shop_id = $(this).attr("id"); $.ajax({ url: "&l ...

Generate HTML content using AngularJS

Is there a way to format a string as HTML when using it in the following syntax: <div> {{ text }} </div> Instead of displaying the actual HTML, only the text is shown - for example " ab " ...

Using Bootstrap 4 to Filter Cards by Title and Tag

I'm attempting to develop searchable cards using HTML, JavaScript, and Bootstrap 4, but I'm facing issues with my code. My goal is to filter these three cards using a search bar, based on their title (h5.card-title) and tags (a.badge). Below is ...

What is the best way to connect a fresh post to a different URL in ReactJS and Redux?

Currently, I am working with Redux and ReactJS to develop a discussion platform. One of the key features I am trying to implement is where users can input the title and content of their post, which will then be submitted to create a new post. After submit ...

Issue encountered when attempting to transfer data to MongoDB using custom API

Currently, I have been working on a flutter application that is designed to send data to my custom API built in node js. This API then forwards the data to a MongoDB cluster. While testing the API, everything was functioning correctly and the data was succ ...

Passing a variable from a service to a controller in AngularJS

I recently developed a basic app that includes user authentication based on the guidelines found in this useful resource. The core components of my app are a userAccountService, which manages communication with the server, and a login controller that over ...

The trouble with dynamicHelpers in Nodejs Express

Trying to make my app run smoothly, I've set up the following configurations: app.configure(function(){ app.set('views', __dirname + '/views'); app.enable('jsonp callback'); app.set('view engine', 'j ...

Is there a way to use findByIdAndUpdate() without inadvertently removing any existing data?

Imagine a scenario where there is a mongoose Person model structured as below: const PersonSchema = new mongoose.Schema({ name: String, address: { street: String, number: number } }); Now, consider a method designed for updati ...